我应该如何在Go中定义一个空片段? [英] How should I define an empty slice in Go?
本文介绍了我应该如何在Go中定义一个空片段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
-
var foo [] int
-
foo:= [] int {}
-
foo:= make ([] int,0)
解决方案
<1> is一个零分片。
$ b $ 2)和3)是非零零长度为零和容量为零的片。
没有一个选项分配内存。
所有选项在Go代码中都经常使用。
因为 len
, cap
和 append
使用nil slices,1)通常可以与2)和3)交换使用。
Or more precisely, it seems like I could do any of these three things. Is there any difference between them? Which is the best and why?
var foo []int
foo := []int{}
foo := make([]int, 0)
解决方案
1) is a nil slice.
2) and 3) are non-nil slices with length zero and capacity zero.
None of the options allocate memory.
All of the options are used commonly in Go code.
Because len
, cap
and append
work with nil slices, 1) can often be used interchangeably with 2) and 3).
这篇关于我应该如何在Go中定义一个空片段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文