切片的零值不是零
我按照以下示例 https://tour.golang.org/moretypes/10
我修改了希望得到相同结果的代码。我没有。这是一个错误还是文档错误?旅游状态
I was following the example https://tour.golang.org/moretypes/10 I modified the code expecting to get the same result. I did not. Is this a bug, or a documentation error? The tour states
一个零切片的长度和容量为0
A nil slice has a length and capacity of 0.
我的y变量的长度和容量都是0.
My y variable has a length and capacity of 0.
package main
import "fmt"
func myPrint(z []int) {
fmt.Println(z, len(z), cap(z))
if z == nil {
fmt.Println("nil!")
}
}
func main() {
var z []int
y := []int {}
myPrint(z)
myPrint(y)
}
这是我的输出。
[] 0 0
nil!
[] 0 0
我期待第二个零〜为什么没有我得到了它?
I was expecting a second "nil"~ Why didn't I get it?
您引用的doc指出 nil slice的长度和容量均为0 ,但不是每个长度和零容量片都是零片。
The doc you referenced to states that A nil slice has a length and capacity of 0 but not that every slice of length and capacity of zero is a nil slice.
这支持 len
和 cap
指向未指定(nil)的指针(片)。否则,我们需要首先检查非零。
This is a convenience to support len
and cap
on pointers (of slices) which are unassigned (nil). Otherwise we would need to check for non-nil first.
指针是理解我认为的问题的关键词。在第一种情况下,你有一个零指针,在第二种情况下你已经分配了slice,但它是空的。这可以适用于任何结构:
Pointer is key word here to understand the problem I think. In the first case you have a nil pointer, in the second case you have allocated slice, but it's empty. This would hold for any structure:
package main
import "fmt"
func main() {
var s *struct{}
fmt.Println(s) // <nil>
s = &struct{}{}
fmt.Println(s) // &{}
}