英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论