首頁 > 後端開發 > Golang > 主體

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

王林
發布: 2024-02-06 09:45:11
轉載
561 人瀏覽過

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
最新問題
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!