Go make

What is ‘make’ and ‘new’[1]

// The make built-in function allocates and initializes an object of type
173 // slice, map, or chan (only). Like new, the first argument is a type, not a
174 // value. Unlike new, make's return type is the same as the type of its
175 // argument, not a pointer to it. The specification of the result depends on
176 // the type:
177 // Slice: The size specifies the length. The capacity of the slice is
178 // equal to its length. A second integer argument may be provided to
179 // specify a different capacity; it must be no smaller than the
180 // length. For example, make([]int, 0, 10) allocates an underlying array
181 // of size 10 and returns a slice of length 0 and capacity 10 that is
182 // backed by this underlying array.
183 // Map: An empty map is allocated with enough space to hold the
184 // specified number of elements. The size may be omitted, in which case
185 // a small starting size is allocated.
186 // Channel: The channel's buffer is initialized with the specified
187 // buffer capacity. If zero, or the size is omitted, the channel is
188 // unbuffered.
189 func make(t Type, size ...IntegerType) Type
190
191 // The new built-in function allocates memory. The first argument is a type,
192 // not a value, and the value returned is a pointer to a newly
193 // allocated zero value of that type.
194 func new(Type) *Type

make or new[2]

Things you can do with make that you can't do any other way:

  • Create a map with space preallocated
  • Create a slice with space preallocated or with len != cap
func newInt1() *int { return new(int) }func newInt2() *int {
var i int
return &i
}

Reference

[1]https://golang.org/src/builtin/builtin.go

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Jimmy Shen

Jimmy Shen

Data Scientist/MLE/SWE @takemobi