patterngoCritical
Correct way to initialize empty slice
Viewed 0 times
emptysliceinitializecorrectway
Problem
To declare an empty slice, with a non-fixed size,
is it better to do:
or:
Just wondering which one is the correct way.
is it better to do:
mySlice1 := make([]int, 0)or:
mySlice2 := []int{}Just wondering which one is the correct way.
Solution
The two alternative you gave are semantically identical, but using
You also have the option to leave it with a
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
None of the above options will cause any allocation, as pointed out by @ArmanOrdookhani.
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 []intAs 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.
Code Snippets
var myslice []intContext
Stack Overflow Q#29164375, score: 495
Revisions (0)
No revisions yet.