Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

go

What is Golang function make(t Type, size ...IntegerType) type?

Muhammad Ashir

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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.

RELATED TAGS

go

CONTRIBUTOR

Muhammad Ashir
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring