Golang Make Function With Examples: All You Need to Know

Robin
Updated on November 15, 2023

The make function is a built-in function in Golang that helps us to create slices, maps, and channels. It's a super handy tool that not only creates these objects but also sets them up for immediate use.

It allocates and initializes an object of a specified type, returning a value of the corresponding type.

Syntax

          make(Type, length, capacity)

        
  • Type: The type of object you want to create, like a slice, map, or channel.
  • length: This is the initial length or size you want to set. It tells how much space you need to store your data. This is only applicable to slices and channels.
  • capacity: The total capacity you want to allocate. It helps you avoid resizing the slice repeatedly when you want to add more elements. This is only applicable to slices. The capacity must be greater than or equal to size.

Creating Slices with Golang make() Function

Let's create a slice of integers with a length of 5 and a capacity of 10.

          package main
import "fmt"

func main() {
    slice := make([]int, 5, 10)
    slice[0] = 34
    fmt.Println(slice)
}

        

The length is the number of elements in the slice, and the capacity is the size of the underlying array.


Creating Maps with make() Function in Golang

To create a map using the make() function, you have to pass its type. You can't provide any other argument to this function while creating a map.

          package main
import "fmt"

func main() {
    myMap := make(map[string]string)
    myMap["lang"] = "Golang"
    fmt.Println(myMap["lang"])
}

        

Here I am creating a map whose keys and values will be string. It will also return and initialize an empty map with the same type.


Creating Channels with Golang make() Function

To create a channel, pass its type to the make() function. You can also provide the size of your channel as the second argument in this function.

          package main
import "fmt"

func main() {
    myChannel := make(chan int, 1)
    myChannel <- 15
    fmt.Println(<-myChannel)
}
        

Here I am creating a buffered channel of integers with a capacity of 1. Now I can send any value to this channel and read from it.

This is how you can use the make() function to create slices, maps, and channels in your Golang program.

Related Posts