According to https://play.golang.org/p/7RPExbwOEU they all print the same and have the same length and capacity. Is there a difference between the three ways to initialize a slice? Is there a preferred way? I find myself using both make([]int, 0)
and []int{}
with the same frequency.
New does not initialize the memory, it only zeros it. It returns a pointer to a newly allocated zero value. Make creates slices, maps, and channels only, and it returns them initialized.
Golang make() is a built-in slice function used to create a slice. The make() function takes three arguments: type, length, and capacity, and returns the slice. To create dynamically sized arrays, use the make() function. The make() function allocates a zeroed array and returns a slice that refers to that array.
Slices in Go and Golang The basic difference between a slice and an array is that a slice is a reference to a contiguous segment of an array. Unlike an array, which is a value-type, slice is a reference type. A slice can be a complete array or a part of an array, indicated by the start and end index.
Using the keyword new to initialize a struct in Golang gives the user more control over the values of the various fields inside the struct .
This initializes a 0 length slice.
make([]int, 0)
Using make
is the only way to initialize a slice with a specific capacity different than the length. This allocates a slice with 0 length, but a capacity of 1024.
make([]int, 0, 1024)
This is a slice literal, which also initializes a 0 length slice. Using this or make([]int, 0)
is solely preference.
[]int{}
This initializes a pointer to a slice, which is immediately dereferenced. The slice itself has not been initialized and will still be nil, so this essentially does nothing, and is equivalent to []int(nil)
*new([]int)
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