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.
Empty slice can be generated by using Short Variable Declarations eg. foo := []string{} or make function.
An empty slice has a reference to an empty array. It has zero length and capacity and points to a zero-length underlying array.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With