The function make is describe like this:
func make(Type, size IntegerType) Type
When we use make for slicing sometimes it shows like:
make([]int, 0, 10)
So my question is:
How can the make function take three parameters? The size IntegerType is not Vararg. I'm confused...
The make function is one of a bunch of built-in functions that are allowed to do things that you cannot achieve (at least not cleanly and easily) in your Go code.
It has a number of overloaded forms for creating maps, channels and slices (see
https://golang.org/ref/spec#Making_slices_maps_and_channels) :
Your confusion probably stems from https://golang.org/pkg/builtin/#make which shows make as having the signature func make(Type, size IntegerType) Type.
If you look closer in that section, you would also see an indication that make can have a third argument:
Slice: The size specifies the length. The capacity of the slice is equal to its length. A second integer argument may be provided to specify a different capacity; it must be no smaller than the length, so make([]int, 0, 10) allocates a slice of length 0 and capacity 10.
You can also notice that make can also be used without its integer argument:
Map: An initial allocation is made according to the size but the resulting map has length 0. The size may be omitted, in which case a small starting size is allocated.
Channel: The channel's buffer is initialized with the specified buffer capacity. If zero, or the size is omitted, the channel is unbuffered.
The make() function is not a regular function, is a builtin function being part of the language specification. What you see in the builtin package (builtin.make()) is only for documentation purposes. That is not the actual signature of the function. The 3rd optional parameter is the capacity, which may only be provided when you're creating a slice.
It's described in the spec: Making slices, maps and channels:
make(T, n) slice slice of type T with length n and capacity n
make(T, n, m) slice slice of type T with length n and capacity m
And also mentioned at Slice types:
A new, initialized slice value for a given element type
Tis made using the built-in functionmake, which takes a slice type and parameters specifying the length and optionally the capacity. A slice created with make always allocates a new, hidden array to which the returned slice value refers. That is, executingmake([]T, length, capacity)produces the same slice as allocating an array and slicing it, so these two expressions are equivalent:
make([]int, 50, 100) new([100]int)[0:50]
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