Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct way to initialize empty slice

Tags:

arrays

slice

go

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.

like image 511
eouti Avatar asked Mar 20 '15 10:03

eouti


People also ask

How do you declare an empty slice?

Empty slice can be generated by using Short Variable Declarations eg. foo := []string{} or make function.

What defines an empty slice?

An empty slice has a reference to an empty array. It has zero length and capacity and points to a zero-length underlying array.

Is empty slice nil?

To tell if a slice is empty, simply compare its length to 0 : len(s) == 0 . It doesn't matter if it's the nil slice or a non- nil slice, it also doesn't matter if it has a positive capacity; if it has no elements, it's empty.


2 Answers

The two alternative you gave are semantically identical, but using make([]int, 0) will result in an internal call to runtime.makeslice (Go 1.16).

You also have the option to 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.

A nil slice will however json.Marshal() into "null" whereas an empty slice will marshal into "[]", as pointed out by @farwayer.

None of the above options will cause any allocation, as pointed out by @ArmanOrdookhani.

like image 198
ANisus Avatar answered Sep 20 '22 22:09

ANisus


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.

See similar questions:

What is the point of having nil slice and empty slice in golang?

nil slices vs non-nil slices vs empty slices in Go language

like image 26
icza Avatar answered Sep 21 '22 22:09

icza