Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between make([]int, 0), []int{}, and *new([]int)?

Tags:

slice

go

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.

like image 974
yefim Avatar asked Mar 14 '17 19:03

yefim


People also ask

What is the difference between make () and new ()?

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.

What does make () do in Golang?

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.

What is the difference between Slice and array in Golang?

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.

What does New do in Golang?

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 .


1 Answers

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)
like image 111
JimB Avatar answered Nov 15 '22 07:11

JimB