当前位置: 动力学知识库 > 问答 > 编程问答 >

arrays - Golang - 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)

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.

网友答案:

They are equivalent. See this code:

mySlice1 := make([]int, 0)
mySlice2 := []int{}
fmt.Println("mySlice1", cap(mySlice1))
fmt.Println("mySlice2", cap(mySlice2))

Output:

mySlice1 0
mySlice2 0

Both slices have 0 capacity which implies both slices have 0 length (cannot be greater than the capacity) which implies both slices have no elements. This means the 2 slices are identical in every aspect.

分享给朋友:
您可能感兴趣的文章:
随机阅读: