dongmaopan5738 2013-02-27 21:03
浏览 140
已采纳

len方法未定义

I've been reading the [golang-book]: http://www.golang-book.com and completing the excercises as I go along. In Chapter 6, there is an exercise that must find the smallest element in an unsorted list[x].

I have the following code but somehow I don't know why the method length (len) gives me an error on line 14: x.len undefined (type []int has no field or method 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])
        }
    }
}

The logic I used was Googled so perhaps there is no len method on arrays? Any help is greatly appreciated.

  • 写回答

3条回答 默认 最新

  • 普通网友 2013-02-27 21:07
    关注

    Arrays and slices do not have a len() method. The len() function is a language built-in.

    So your code

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

    Should be

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

    Here is a working version in the playground.

    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 < len(x); i++ {
            if x[i] < small { 
            fmt.Println(x[i]);
            }
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置