go - 为什么这个零长度和零容量 slice 不为零?

标签 go

我正在通过 Go tutorial我上了一堂关于零 slice 的课,上面写着:

A nil slice has a length and capacity of 0 and has no underlying array.



为了表明这一点,他们提供了这个有效的代码

package main

import "fmt"

func main() {
    var s []int 
    fmt.Println(s, len(s), cap(s))
    if s == nil {
        fmt.Println("nil!")
    }
}

但是,我尝试进行实验并替换了 var s []ints := []int{} .控制台仍然打印 [] 0 0与第一种情况一样,但不再是 nil!字符串。那么为什么是第一个nil而另一个不是?

最佳答案

对于 s := []int{} :
因为是初始化 到具有底层数组、长度和容量的新类型(例如 struct)

A slice, once initialized, is always associated with an underlying array that holds its elements.



对于 var s []intSlice types :

The value of an uninitialized slice is nil.



The zero value :

When storage is allocated for a variable, either through a declaration or a call of new, or when a new value is created, either through a composite literal or a call of make, and no explicit initialization is provided, the variable or value is given a default value. Each element of such a variable or value is set to the zero value for its type: false for booleans, 0 for numeric types, "" for strings, and nil for pointers, functions, interfaces, slices, channels, and maps. This initialization is done recursively, so for instance each element of an array of structs will have its fields zeroed if no value is specified.
These two simple declarations are equivalent:


var i int
var i int = 0


type T struct { i int; f float64; next *T }
t := new(T)

以下成立:
t.i == 0
t.f == 0.0
t.next == nil

之后也是如此
var t T

我希望这有帮助。

关于go - 为什么这个零长度和零容量 slice 不为零?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58556653/

相关文章:

google-app-engine - 如何调试 "No default robot"?

debugging - 有没有办法为链接到 Go 的 CGO 代码获取调试符号?

regex - 如何使用 golang 正则表达式引用组

go - 解码到结构时从 JSON 转换值

java - 带有数据流的 Apache Beam Go SDK

json - 如何解析 JSON 提取数组

go - 如何在golang中转换类型?

go - 解码嵌套在 JSON 对象中的数组

macos - 去构建并执行: fork/exec: permission denied

opengl 3.3 z-fighting 正交 2d View