切片(slice)的声明和初始化之间的区别是什么?

huangapple go评论85阅读模式
英文:

difference between slice declaration and initialization

问题

a和b之间有什么区别?我知道reflect.DeepEqual认为它们不相等,我也知道a是nil。是否有内置函数可以轻松显示它们之间的区别?

var a []foo
b := []foo{}
英文:

What is the difference between a and b? I know that reflect.DeepEqual considers them not equal and I know that a is nil. Are there built in functions that easily show the difference?

var a []foo
b := []foo{}

答案1

得分: 3

fmt.Println(a == nil, b == nil)

打印结果为 true false(Playground: http://play.golang.org/p/E0nQP8dVyE)。a 是一个空切片,而 b 是一个空的切片。在实践中它们之间没有太大的区别,但通常情况下,比如在查询数据库的函数中,一个空切片表示没有结果(由于错误或其他原因),而一个空的切片表示找不到相关信息。

关于底层的区别,请参考Russ Cox的Go数据结构文章。

英文:
fmt.Println(a == nil, b == nil)

prints true false (Playground: http://play.golang.org/p/E0nQP8dVyE). a is a nil slice, while b is just an empty slice. There isn't a lot of difference in practice, but usually, say in a function that queries a database, a nil slice means no result (due to error or something else), while an empty slice - that it could not find the information.

For the difference on the lower level, see Russ Cox's Go Data Structures article.

答案2

得分: 2

a零值使其为nil

> 对于指针、函数、接口、切片、通道和映射,都是nil

相反,b被初始化为短声明

英文:

The zero value for a makes it nil.

> nil for pointers, functions, interfaces, slices, channels, and maps.

As opposed to b, which is initialized as a short declaration.

huangapple
  • 本文由 发表于 2015年5月13日 13:48:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/30206633.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定