猿问

len方法未定义

我一直在阅读[golang-book]:http://www.golang-book.com,并按照自己的意愿完成练习。在第6章中,有一项练习必须在未排序列表[x]中找到最小的元素。


我有以下代码,但是以某种方式我不知道为什么方法长度(len)在第14行给我一个错误:x.len undefined(类型[] int没有字段或方法len)


package main


import "fmt"


func main() {

    x := []int{

        48, 96, 86, 68,

        57, 82, 63, 70,

        37, 34, 83, 27,

        19, 97, 9, 17,

    }


    small := x[0]

    for i := 1; i < x.len(); i++ {

        if x[i] < small {

            fmt.Println(x[i])

        }

    }

}

我使用的逻辑是谷歌搜索的,所以也许数组上没有 len 方法?任何帮助是极大的赞赏。


缥缈止盈
浏览 277回答 3
3回答

尚方宝剑之说

数组和切片没有len()方法。len()函数是内置的语言。所以你的代码for i := 1; i < x.len(); i++ {应该for i := 1; i < len(x); i++ {这是操场上的工作版本。package mainimport "fmt"func main(){&nbsp; &nbsp; x := []int{&nbsp; &nbsp; &nbsp; &nbsp; 48,96,86,68,&nbsp; &nbsp; &nbsp; &nbsp; 57,82,63,70,&nbsp; &nbsp; &nbsp; &nbsp; 37,34,83,27,&nbsp; &nbsp; &nbsp; &nbsp; 19,97, 9,17,&nbsp; &nbsp; }&nbsp; &nbsp;&nbsp; &nbsp; small := x[0]&nbsp; &nbsp; for i := 1; i < len(x); i++ {&nbsp; &nbsp; &nbsp; &nbsp; if x[i] < small {&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println(x[i]);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}

慕田峪7331174

len()不是切片的方法。这是一个全局功能。你想说len(x)。package mainimport "fmt"func main() {&nbsp; &nbsp; x := []int{&nbsp; &nbsp; &nbsp; &nbsp; 48, 96, 86, 68,&nbsp; &nbsp; &nbsp; &nbsp; 57, 82, 63, 70,&nbsp; &nbsp; &nbsp; &nbsp; 37, 34, 83, 27,&nbsp; &nbsp; &nbsp; &nbsp; 19, 97, 9, 17,&nbsp; &nbsp; }&nbsp; &nbsp; small := x[0]&nbsp; &nbsp; for i := 1; i < len(x); i++ {&nbsp; &nbsp; &nbsp; &nbsp; if x[i] < small {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Println(x[i])&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}
随时随地看视频慕课网APP

相关分类

Go
我要回答