gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 22:38:51 26 4
gpt4 key购买 nike

我正在通过 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com