Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can the make function take three parameters?

Tags:

function

go

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...

like image 608
Xie Jinke Avatar asked Apr 01 '16 05:04

Xie Jinke


2 Answers

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.

like image 174
Dimitar Dimitrov Avatar answered Dec 17 '22 22:12

Dimitar Dimitrov


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 T is made using the built-in function make, 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, executing

make([]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]
like image 22
icza Avatar answered Dec 17 '22 22:12

icza