类型 []int 没有字段或方法 length

huangapple go评论98阅读模式
英文:

type []int has no field or method length

问题

我有以下代码 -

package "main"

var fibonacciNumbers = []int{0, 1}

func getIthFibo(i int) int {
    if i < fibonacciNumbers.length {
        return fibonacciNumbers[i]
    }
    ...
}

然而,在if条件处我遇到了一个错误 -

fibonacciNumbers.length未定义 - 类型[]int没有length字段或方法

我理解的是我创建了一个包含元素0和1的切片 - 所以它应该有长度为2,但我得到了上述错误。

英文:

I have the following code -

package &quot;main&quot;

var fibonacciNumbers = []int{0, 1}

func getIthFibo(i int) int {
    if i &lt; fibonacciNumbers.length {
        return fibonacciNumbers[i]
    }
    ...
}

However, I get an error at the if condition -

fibonacciNumbers.length undefined - type []int has no field or method length

What I understood was that I created a slice with the elements 0 and 1 - so it should have a length of 2 but I get the above error.

答案1

得分: 5

获取切片长度的Go语言方式是使用len函数:

if i < len(fibonacciNumbers)
英文:

The golang way of getting a slices length is to use the len function:

if i &lt; len(fibonacciNumbers)

huangapple
  • 本文由 发表于 2015年1月7日 01:47:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/27804218.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定