Golang - 正确的初始化空片的方法 [英] Golang - correct way to initialize empty slice
问题描述
要声明一个空的切片,其大小不固定,
最好做:
mySlice1:= make([] int,0)
或者:
mySlice2:= [] int {}
只是想知道哪一个是正确的方法。
干杯
您给出的两种选择在语义上是相同的,我会假设他们会产生相同的汇编指令。
为了避免不必要的分配,如果你最终不使用分片,你可以使用 nil
value:
var myslice [] int
code>
正如 Golang.org博客:
一个零切片在功能上等价于一个零长切片,即使它没有指向任何东西。它的长度为零,可以附加到分配。
To declare an empty slice, with a non-fixed size, is it better to do :
mySlice1 := make([]int, 0)
or :
mySlice2 := []int{}
Just wondering which one is the correct way.
Cheers
The two alternative you gave are semantically identical, and I would assume they produce the same assembly instructions.
To avoid an unnecessary allocation, in case you will end up not using the slice, you can leave it with a nil
value:
var myslice []int
As written in the Golang.org blog:
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.
这篇关于Golang - 正确的初始化空片的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!