首頁  >  文章  >  後端開發  >  Go錯誤:int型別的值作為int值

Go錯誤:int型別的值作為int值

王林
王林轉載
2024-02-06 09:45:11564瀏覽

Go錯誤:int型別的值作為int值

問題內容

我是程式設計和 stackoverflow 的初學者。

我必須在 go 中建立一個遞歸函數來新增陣列的元素,如果陣列的長度為 0,則傳回 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)
}

它給了我這個錯誤,但我不明白。

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

為什麼會出現此錯誤以及如何修復它?


正確答案


這是你的問題:

您看到的錯誤訊息是因為您嘗試將 int 值傳遞給 Suma 函數,該函數需要一個 int 切片。

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

以上是Go錯誤:int型別的值作為int值的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:stackoverflow.com。如有侵權,請聯絡admin@php.cn刪除