Golang make() Function

Golang make() function is “used for slices, maps, or channels.” The make() function allocates memory on the heap and initializes and puts zero or empty strings into values.

The make() function assigns the underlying array with a size equal to the given capacity and returns the slice, which refers to the underlying array.

Syntax

func make([]T, len, cap) []T

Parameters

  1. t Type: The allocated type and for which the reference will be returned. Example: map, slice, etc.
  2. size: The size of the container.
  3. capacity: The total capacity that will be allocated. capacity must be greater than or equal to size.

Return value

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

Example: How to Use make() function in Golang

package main

import "fmt"

func main() {

 // Creating an array of size 6
 // and slice this array till 3
 // and return the reference of the slice
 // Using make() function
 var sliceA = make([]int, 3, 6)
 fmt.Printf("SliceA = %v, \nlength = %d, \ncapacity = %d\n",
 sliceA, len(sliceA), cap(sliceA))

 // Creating another array of size 6
 // and return the reference of the slice
 // Using make() function
 var sliceB = make([]int, 6)
 fmt.Printf("SliceB = %v, \nlength = %d, \ncapacity = %d\n",
 sliceB, len(sliceB), cap(sliceB))
}

Output

SliceA = [0 0 0],
length = 3,
capacity = 6
SliceB = [0 0 0 0 0 0],
length = 6,
capacity = 6

FAQ

What is the make() function in Golang?

Golang’s make() function optimizes dynamic data structures like slices, maps, and channels.

The make() function creates a new, empty object of a specified type with a pre-allocated amount of memory to store elements.

What is the difference between new and make functions in Golang?

The new() function allocates memory for an object of a specified type, while the make() function creates and initializes dynamic data structures.

The new() function returns a pointer to a newly allocated zero value of a specified type, while the make() function returns a newly created and initialized object of the specified type.

Can the make() function create objects of different types?

Yes, the make() function creates objects of different types, like slices, maps, and channels, as long as the type is specified correctly in the call to make.

How can dynamic data structures be created using the make function()?

Golang make() function creates and initializes slices, maps, and channels.

The make() function cannot create objects like structs or arrays.

That’s it.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.