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

Go error: value of type int as int value

王林
Release: 2024-02-06 09:45:11
forward
601 people have browsed it

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)
}
Copy after login

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>
Copy after login

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)
}

Copy after login

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!

Related labels:
source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template