切片中的长度和容量方法

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

Length and capacity methods in slices

问题

阅读有关Golang中数组和切片的内容。

为什么要使用内置函数,如lencap,而不是类似的切片对象方法?

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

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

为什么要污染全局命名空间?为什么不使用面向对象的风格?

此外,是否存在这样的方法,可以替代内置函数使用?

英文:

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

得分: 2

这个问题有一个常见问题解答,但是我来解释一下:

len()cap()是内置函数,因为编译器能够理解它们。你不能自己替换它们,它们是核心语言的一部分,与方法不同,不要混淆它们。

在Go语言中,切片由三部分组成:长度、容量和指向底层内存的指针。例如,reflect包中的定义:

type SliceHeader struct {
        Data uintptr
        Len  int
        Cap  int
}

len(x)只是从切片结构中读取长度,所以它相当于x.Len的简写形式,编译器能够理解并进行相应的优化。

英文:

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.

huangapple
  • 本文由 发表于 2014年4月1日 01:53:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/22768697.html
匿名

发表评论

匿名网友

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

确定