What is Golang function make(t Type, size ...IntegerType) type?
In Golang, make() is used for slices, maps, or channels. make() allocates memory on the heap and initializes and puts zero or empty strings into values. Unlike new(), make() returns the same type as its argument.
-
Slice: The
sizedetermines the length. Thecapacityof the slice is equal to or greater than its length. For instance,make([]int, 0, 10)allots an array of size 10 and returns asliceof length 0 and capacity 10. -
Map: A
mapis allocated with a specified amount of space by default, hence thesizeargument can be left out. -
Channel: The buffer for the
channelis initialized with the given buffer capacity. If the capacity is zero, the channel is unbufferred.
Prototype
func make(t Type, size ...IntegerType) Type
Parameters
t Type: The type that is allocated and for which the reference will be returned. Example: map, slice, etc.size: The size of the container.capacity: The total capacity that will be allocated.capacitymust be greater than or equal tosize.
Return value
make() returns a reference to the map, slice, or channel that is allocated on the memory.
Code
package mainimport "fmt"func main() {mymap := make(map[int]string)mymap[2] = "TWO"fmt.Println(mymap[2])myList := make([]string,2, 10)myList[0] = "London"fmt.Println(myList)myChannel := make(chan int, 1)myChannel <- 10fmt.Println(<-myChannel)}
In the above code, we use the make() function to allocate memory for a map, slice, and channel.
Free Resources