英文:
Length and capacity methods in slices
问题
阅读有关Golang中数组和切片的内容。
为什么要使用内置函数,如len
和cap
,而不是类似的切片对象方法?
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论