Go make
2 min readSep 12, 2020
Make is very powerful. The reason it is powerful is we can see it everywhere. However, I can not really have an intuitive understanding of the logic behind the ‘make’.
In order to be more satisfied with “make”, let’s do more exploration.
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 channel
- Create a map with space preallocated
- Create a slice with space preallocated or with len != cap
It’s a little harder to justify new
. The main thing it makes easier is creating pointers to non-composite types. The two functions below are equivalent. One's just a little more concise:
func newInt1() *int { return new(int) }func newInt2() *int {
var i int
return &i
}
return &i
}
Reference
[1]https://golang.org/src/builtin/builtin.go
[2]https://stackoverflow.com/questions/9320862/why-would-i-make-or-new