dreamMyDream2014 2014-03-31 17:53
浏览 27

切片中的长度和容量方法[关闭]

Reading about arrays and slices in Golang.

Why built-in functions like len and cap are used and not similar methods on slice objects?

if cap(slice) == len(slice) {
    fmt.Println("slice is full!")
}

vs

if slice.cap() == slice.len() {
    fmt.Println("slice is full!")
}

Why polluting the global namespace? Why not using object oriented style?

Also, do such methods exist and can they be used instead of built-in functions?

  • 写回答

1条回答 默认 最新

  • duanruoyu6675 2014-03-31 22:24
    关注

    There is a FAQ entry on this, but here is my take:

    len() and cap() are built in functions because they are understood by the compiler. You can't make your own replacements - they are very much part of the core language in a way that methods aren't, and you shouldn't confuse them with methods.

    In Go a slice is made of three things, a length, a capacity and a pointer to the underlying memory. Eg the definition from reflect

    type SliceHeader struct {
            Data uintptr
            Len  int
            Cap  int
    }
    

    All len(x) does is read the length from the slice structure, so it is shorthand for something like x.Len and the compiler understands that and optimises it accordingly.

    评论

报告相同问题?

悬赏问题

  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集