英文:
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 "main"
var fibonacciNumbers = []int{0, 1}
func getIthFibo(i int) int {
if i < 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 < len(fibonacciNumbers)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论