Home >Backend Development >Golang >Go error: value of type int as int value
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?
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!