go - slice 的零值不为零

标签 go slice

我按照示例 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

我期待第二个“零”~为什么我没有得到它?

最佳答案

nilempty 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, and cap work the same.


Go playground example :

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/

相关文章:

go - 如何在不更改路径的情况下在 Go 中配置二进制名称

go - 如何链接HTML

python - 高斯消元法 - 在 python 中使用切片进行旋转

json - 如何在 Go 中构建结构的递归 slice ?

arrays - 从 Golang 中的数组中选择元素的最惯用方法?

go - 是否自动绑定(bind)函数到结构?

go - 如何在 grpc-gateway 中设置超时?

git - Dockerhub 自动构建多个私有(private)仓库

arrays - go 中没有匿名数组?

python - 根据纬度和经度过滤数据 - Numpy