liveBook · Manning

Make

As explained in Learn Go with Pocket-Sized Projects

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

make is a Go built-in function that allocates and initializes maps, slices, or channels. For maps, an optional size hint makes expected capacity explicit; omitting it or passing zero has the same behavior. section 3.2.1

Use make according to the collection being initialized:

  • Initialize a map with an optional expected size: count := make(map[Book]uint, 451). section 3.2.1
  • Initialize a slice with a length: books := make([]Book, 5) creates five elements that can be indexed immediately. section 3.2.2
  • Initialize a slice with capacity but no elements: books := make([]Book, 0, 5), then grow it with append. section 3.2.2

Counting books with a map

func booksCount(bookworms []Bookworm) map[Book]uint { count := make(map[Book]uint) for _, bookworm := range bookworms { for _, book := range bookworm.Books { count[book]++ } } return count } The map stores each Book as a key and its occurrence count as a uint value. A known number of distinct books can be supplied as a size hint.

Collecting repeated books

var commonBooks []Book for book, count := range booksOnShelves { if count > 1 { commonBooks = append(commonBooks, book) } } A nil slice can grow with append, while make([]Book, 0, 5) reserves capacity without adding elements.

How Learn Go with Pocket-Sized Projects covers it

How deep it goes
Explains allocation, map size hints, and slice length versus capacity, but defers deeper slice internals.
Examples
Demonstrates map counting, explicit map sizing, indexed slices, reserved capacity, and appending repeated books.
What it assumes
Assumes familiarity with maps, slices, range loops, and append while developing slice length and capacity distinctions.
What you can do after
Build it from scratch by choosing map size hints and slice length or capacity for collection-based functions.
How it connects
Connects make with maps, slices, channels, arrays, append, len, and cap.

Also explained in

Compare how 2 books explain make →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Go with Pocket-Sized Projects. The section links point to the parts of the book it draws on.