DMarlon Studio

Lesson 11 · 11 of 20

Maps · Go

Store key-value pairs in a Go map: adding, reading with ok, delete and len, and printing it in the same order every time with sort.Strings.

Go · Maps in DMarlon Studio: the example's code and its output in the terminal

A map links keys to values. map[string]int has string keys and integer values, and the literal pairs them with a colon: "apples": 12. To read, put the key in square brackets: stock["apples"] gives 12.

Assigning to a key changes its value if it exists (pears becomes 8) and creates it if it does not (kiwis). Reading a missing key does not fail: it gives the type's zero value, 0. To find out whether it is really there, ask for a second value: _, ok := stock["bananas"] leaves ok as false.

delete(stock, "plums") removes a key together with its value, and len(stock) counts the ones left: 3.

The order of a Go map is random on purpose: each run may walk it differently. To print it the same way every time, gather the keys into a slice with for key := range stock (lesson 18 covers range), sort them with sort.Strings(keys) and go through them in that order, reading each value with stock[keys[i]].

Code · main.go

package mainimport (	"fmt"	"sort")func main() {	// A map links keys to values: map[keyType]valueType.	stock := map[string]int{"apples": 12, "pears": 5, "plums": 0}	fmt.Println("Apples:", stock["apples"])	// Assigning changes a value or adds a new key.	stock["pears"] = 8	stock["kiwis"] = 20	// A missing key gives the zero value; ok says if it exists.	fmt.Println("Bananas:", stock["bananas"])	if _, ok := stock["bananas"]; !ok {		fmt.Println("We do not sell bananas")	}	delete(stock, "plums")	fmt.Println("Kinds of fruit:", len(stock))	// The order of a map is random: sort the keys first.	keys := make([]string, 0, len(stock))	for key := range stock {		keys = append(keys, key)	}	sort.Strings(keys)	for i := 0; i < len(keys); i++ {		fmt.Printf("%-8s%4d\n", keys[i], stock[keys[i]])	}}

Output · go run main.go

Apples: 12
Bananas: 0
We do not sell bananas
Kinds of fruit: 3
apples    12
kiwis     20
pears      8

Key points

  • map[key]value links keys to values.
  • m[k] = v changes or adds; delete(m, k) removes.
  • A missing key gives the zero value.
  • v, ok := m[k] tells you whether the key exists.
  • Map order is random: sort the keys with sort.Strings.

Exercise

Add a prices map with the price of each fruit and print, in alphabetical order, each fruit with the value of its stock (float64(stock[k]) * prices[k]) and the total at the end.