liveBook · Manning

Make

As explained in Go in Action, Second Edition

make is a Go built-in function that allocates and initializes slices, maps, or channels with a specified type and size parameters.

Go’s built-in make function allocates and initializes slices, maps, and channels. Its arguments depend on the type: slices can specify length and capacity, while channels can specify a buffer capacity. section 4.2.2 section 4.3.1 section 9.4

Choose arguments according to the value’s role:

  • Slices: make([]T, length) creates a slice of zero-valued elements. make([]T, length, capacity) reserves additional backing-array space for growth. Capacity must be at least length; otherwise compilation fails when the compiler can detect the error, or execution panics. section 4.2.2
  • Maps: make(map[K]E) creates an initialized map ready for assignments. A map declared with var is nil, and assigning to it panics. Prefer a map literal when creating and populating a map together. section 4.3.1
  • Channels: make(chan T) creates a channel for communication between goroutines. A capacity can also be supplied, as in make(chan T, 10). Channels can be passed to functions, returned, or stored in structs. section 9.4

Preallocate a slice for growth

items := make([]int, 0, 5) creates an empty slice backed by space for five integers. Its length is zero, so the reserved elements are not yet accessible through the slice. Appending can use that space without creating a new backing array until further capacity is needed. section 4.2.2

Initialize a map before assignment

counts := make(map[int]string) creates an empty map; counts[1] = "one" can then add an entry. Alternatively, map[int]string{1: "one"} initializes and populates the map in one expression. section 4.3.1

Connect a producer and consumer

A feed-fetching function can create an article channel with make, pass it to a saving goroutine, and send fetched articles through it. Closing the channel lets the consumer’s range loop finish after receiving the values. section 9.4

How Go in Action, Second Edition covers it

How deep it goes
Explains slice backing arrays and capacity constraints, map initialization, and channel creation through usage examples.
Examples
Uses preallocated integer slices, integer-to-string maps, and channels for fetching and saving feed articles.
What you can do after
Apply make to initialize collections and create channels, choosing slice capacity for anticipated growth and avoiding nil-map assignment panics.
How it connects
Connects make to append, zero values, nil maps, backing arrays, and goroutines.

Also explained in

Compare how 2 books explain make →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Go in Action, Second Edition. The section links point to the parts of the book it draws on.