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.
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
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.
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
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 byappend, usemake([]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.
nilis also valid.var s []intandvar m map[string]intarenil. Anilslice works withappend,lenandrange; anilmap can be read but writing panics. Usemakeor a literal before writing.- Unbuffered channels (the default) make sender and receiver meet; a buffer lets the sender run ahead until it is full.
makecannot 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.
Related
new(),append(),len(),cap(),close()- Lessons: make and new, Slice internals