Skip to content
Tutorials Center
My learning

Topics

Go Reference ยท Built-in Functions

Go make() function

Reference for Go make(): create slices with a length and capacity, maps with a size hint and channels with a buffer, plus panics and how it differs from new().

make() creates and initializes a slice, a map or a channel. Unlike new(), it returns the value itself (not a pointer), ready to use. These three types are references to internal data structures that must be set up before use; make does that setup.

Each of the three forms takes different arguments: a slice needs a length (and optionally a capacity), a map takes an optional size hint, and a channel takes an optional buffer size.

Go
s := make([]int, 3, 10)        // len 3, cap 10
m := make(map[string]int)      // empty map
c := make(chan string, 4)      // buffered channel

Try it

Go Slices, maps and channels

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Go Length versus capacity, and invalid arguments

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Syntax

Go
make(T, n)         // slice: length n, capacity n
make(T, n, m)      // slice: length n, capacity m
make(T)            // map or unbuffered channel
make(T, n)         // map: size hint n; channel: buffer size n
Form Meaning
make([]T, len) Slice with len zero-valued elements
make([]T, len, cap) Slice with room for cap elements without reallocation
make(map[K]V, hint) Map; hint is optional and only a size estimate
make(chan T, size) Channel; size 0 or omitted means unbuffered

Returns: a value of type T (not *T).

Panics: a negative size or a len larger than cap panics at run time; with constant arguments it is a compile error. Sizes too large for memory also panic.

Usage notes

  • Length is not capacity. make([]int, 5) gives five zeros. If you want to fill by append, use make([]int, 0, 5).
  • Preallocate when you know the size. make([]T, 0, n) avoids repeated reallocation while appending. For maps, a hint avoids rehashing while the map grows.
  • A map hint is not a limit. The map still grows beyond it.
  • nil is also valid. var s []int and var m map[string]int are nil. A nil slice works with append, len and range; a nil map can be read but writing panics. Use make or a literal before writing.
  • Unbuffered channels (the default) make sender and receiver meet; a buffer lets the sender run ahead until it is full.
  • make cannot create arrays, structs or pointers. Use a literal, new() or &T{}.
  • Size arguments can be any integer type or an untyped constant representable as int.