Home  >  Article  >  Backend Development  >  Go error: value of type int as int value

Go error: value of type int as int value

王林
王林forward
2024-02-06 09:45:11562browse

Go error: value of type int as int value

Question content

I am a beginner in programming and stackoverflow.

I have to create a recursive function in go that adds elements of an array and returns 0 if the length of the array is 0.

func Suma(vector []int) int {
    n := len(vector)
    if n == 0 {
        return 0
    } else {
        return Suma(vector[n] + vector[n-1])
    }
}

func main() {
    fmt.Println("Hello, 世界")
    vector := []int{1, 2, 3, 4, 5}
    res := Suma(vector)
    fmt.Println(res)
}

It gives me this error but I don't understand it.

<code>
cannot use vector[n] + vector[n - 1] (value of type int) as []int value in argument to Suma
</code>

Why does this error occur and how to fix it?


Correct answer


This is your question:

The error message you are seeing is because you are trying to pass an int value to the Suma function, which expects an int slice.

package main

import "fmt"

func Suma(vector []int) int {
    n := len(vector)
    if n == 0 {
        return 0
    } else {
        // You should call Suma recursively with a slice of the vector, excluding the last element.
        // Also, you need to add the current element (vector[n-1]) to the sum.
        return vector[n-1] + Suma(vector[:n-1])
    }
}

func main() {
    fmt.Println("Hello, 世界")
    vector := []int{1, 2, 3, 4, 5}
    res := Suma(vector)
    fmt.Println(res)
}

The above is the detailed content of Go error: value of type int as int value. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete
Previous article:Escape "/" in templatesNext article:Escape "/" in templates