map
A Go collection that stores values by key, such as service name to port number, and looks them up quickly.
In more detail
Write the type as map[KeyType]ValueType. Reading a missing key returns the zero value, so use the comma ok form to tell missing from stored zero. A nil map can be read but writing to it panics, so create it with make or a literal first. Iteration order is deliberately random.
Example
ports := map[string]int{"http": 80, "https": 443}Related terms
- comma ok idiom — The Go pattern of receiving a second true-or-false result, as in value, ok := m[key], to learn whether an operation really found something.
- make (built-in) — The built-in Go function that creates a ready-to-use map, slice or channel, such as make(map[string]bool) or make(chan string).
- nil — The Go value meaning nothing or not set, which is the zero value for pointers, slices, maps, channels, functions, interfaces and errors.
- zero value — The value Go gives a variable automatically when you declare it without one: 0 for numbers, "" for strings, false for booleans and nil for pointers, slices and maps.
- range loop — A Go for loop with the range keyword that visits each element of a slice, map, string or channel in turn.
Taught in
- Variables, Typing, and Zero Values — Concurrent Systems Programming with Go
- Arrays, Slices, and Maps — Concurrent Systems Programming with Go
- Type Assertions and the Empty Interface — Concurrent Systems Programming with Go
- Writing Table Driven Tests — Concurrent Systems Programming with Go
- Parsing JSON with encoding/json — Concurrent Systems Programming with Go
- Executing Concurrent Checks — Concurrent Systems Programming with Go
- Handling Timeouts and Errors — Concurrent Systems Programming with Go
- Exporting Results as JSON — Concurrent Systems Programming with Go