ProgramGuru

The make() Function

Start with The make() Function

The built-in make function initializes the runtime structures for slices, maps and channels, returning a value of the requested type.

What you’ll learn

  • Explain the main purpose of the make() function.
  • Read and run the complete Go example in this lesson.
  • Apply the concept and recognize common mistakes.

Understand the idea

Use make([]int, 2, 5) for a slice with length 2 and capacity 5. Use make(map[string]int) for an empty writable map. For a buffered channel, use a form such as make(chan int, 2).

Unlike new(T), make(T, ...) returns a T, not a *T. It does not apply to ordinary scalars or structs. Channels are explained in the concurrency group; the example here uses just a slice and a map.

Visualize how it works

Follow this diagram before executing the example. Check where a value or decision changes what runs next.

Visual explanation for makemake initializes the runtime representation of a collection.make sliceStep 1len 2, cap 5Step 2make mapStep 3Map is writableStep 4make initializes the runtime representation of a collection.
make initializes the runtime representation of a collection.

Run a complete Go example

This example is a complete program. Save it as main.go or paste it into the Go Playground.

Go code

package main

import "fmt"

func main() {
	numbers := make([]int, 2, 5)
	numbers[0], numbers[1] = 4, 8
	counts := make(map[string]int)
	counts["apples"] = 3
	fmt.Println("Slice:", numbers)
	fmt.Println("Length/capacity:", len(numbers), cap(numbers))
	fmt.Println("Apples:", counts["apples"])
}

Output

Slice: [4 8]
Length/capacity: 2 5
Apples: 3

Trace what the program does

make creates a slice with two accessible zero-valued slots and a capacity of five. Setting the first two elements produces [4 8]. It also creates a map that accepts the apples entry.

Avoid common mistakes

  • make([]int, 2, 5) exposes indexes 0 and 1, not indexes through 4.
  • make returns a slice, map or channel value, not a pointer to one.

Try it yourself

Make a slice with length 1 and capacity 3. Append a number and print its new length and capacity.

Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.

Check your understanding

Which is an appropriate use of make?
Choose one answer. You can try again.

Answer and explanation

make(map[string]int)

Correct. make creates a slice with two accessible zero-valued slots and a capacity of five.

What you should remember

You have practiced The make() Function in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.

Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: Understanding Go Memory Management →