我按照示例 https://tour.golang.org/moretypes/10 我修改了期望得到相同结果的代码。我没有。这是一个错误,还是一个文档错误?旅游状态
A nil slice has a length and capacity of 0.
我的 y 变量的长度和容量为 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
我期待第二个“零”~为什么我没有得到它?
最佳答案
nil
与 empty
slice
如果我们想到这样的 slice :
[pointer] [length] [capacity]
然后:
nil slice: [nil][0][0]
empty slice: [addr][0][0] // it points to an address
From: "Go in action" book:
nil slice
They’re useful when you want to represent a slice that doesn’t exist, such as when an exception occurs in a function that returns a slice.
// Create a nil slice of integers. var slice []int
empty slice
Empty slices are useful when you want to represent an empty collection, such as when a database query returns zero results.
// Use make to create an empty slice of integers. slice := make([]int, 0) // Use a slice literal to create an empty slice of integers. slice := []int{}
👉 Regardless of whether you’re using a nil slice or an empty slice, the built-in functions
append
,len
, andcap
work the same.
package main
import (
"fmt"
)
func main() {
var nil_slice []int
var empty_slice = []int{}
fmt.Println(nil_slice == nil, len(nil_slice), cap(nil_slice))
fmt.Println(empty_slice == nil, len(empty_slice), cap(empty_slice))
}
打印:
true 0 0
false 0 0
关于go - slice 的零值不为零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30806931/