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 size determines the length. The capacity of the slice is equal to or greater than its length. For instance, make([]int, 0, 10) allots an array of size 10 and returns a slice of length 0 and capacity 10.

  • Map: A map is allocated with a specified amount of space by default, hence the size argument can be left out.

  • Channel: The buffer for the channel is 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. capacity must be greater than or equal to size.

Return value

make() returns a reference to the map, slice, or channel that is allocated on the memory.

Code

package main
import "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 <- 10
fmt.Println(<-myChannel)
}

In the above code, we use the make() function to allocate memory for a map, slice, and channel.

Copyright ©2024 Educative, Inc. All rights reserved