初始化空切片的正确方法 [英] Correct way to initialize empty slice
问题描述
要声明一个不固定大小的空片, 这样做更好吗?
To declare an empty slice, with a non-fixed size, is it better to do:
mySlice1 := make([]int, 0)
或:
mySlice2 := []int{}
只是想知道哪种方法是正确的.
Just wondering which one is the correct way.
推荐答案
您提供的两个选择在语义上是相同的,但是使用make([]int, 0)
会导致对 runtime.makeslice 的内部调用(转到1.14).
The two alternative you gave are semantically identical, but using make([]int, 0)
will result in an internal call to runtime.makeslice (Go 1.14).
您还可以选择将其保留为nil
值:
You also have the option to leave it with a nil
value:
var myslice []int
如 Golang.org博客中所述:
nil切片在功能上等效于零长度切片,即使它没有指向任何内容.它的长度为零,可以附加分配.
a nil slice is functionally equivalent to a zero-length slice, even though it points to nothing. It has length zero and can be appended to, with allocation.
但是,如@farwayer所指出的,nil
切片将json.Marshal()
放入"null"
,而空切片将封送到"[]"
.
A nil
slice will however json.Marshal()
into "null"
whereas an empty slice will marshal into "[]"
, as pointed out by @farwayer.
如@ArmanOrdookhani所述,以上选项均不会导致任何分配.
None of the above options will cause any allocation, as pointed out by @ArmanOrdookhani.
这篇关于初始化空切片的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!