A customer asks "How much is the Iced Tea?" Bimo doesn't read the price list on the wall from the top line down. He looks straight at the Iced Tea line: 5,000.
That is how a map works: you give it the key, and the map hands you the value straight away, without walking through its items one by one. The dish name is the key, the price is the value. In JavaScript this is like an object. The difference is that in Go every key has one type, and so does every value.
Making a map
prices := map[string]int{
"Tendon Meatballs": 15,
"Chicken Noodles": 12,
"Iced Tea": 5,
}
fmt.Println(prices) // map[Chicken Noodles:12 Iced Tea:5 Tendon Meatballs:15]
fmt.Println(prices["Tendon Meatballs"]) // 15
fmt.Println(len(prices)) // 3
map[string]intmeans the keys are strings and the values are ints.- Every pair is written
key: value, and the last line ends with a comma too. prices["Tendon Meatballs"]takes the value of that key.len(prices)is the number of pairs.fmt.Printlnprints a map with its keys sorted, not in the order you wrote them.- An empty map ready to be filled:
make(map[string]int)ormap[string]int{}.
Add, change, delete
prices["Iced Orange"] = 6 // a new key: added
prices["Iced Tea"] = 4 // a key that exists: its value is replaced
delete(prices, "Chicken Noodles") // deleted
delete(prices, "Chicken Soup") // the key isn't there: nothing happens
fmt.Println(prices, len(prices))
map[Iced Orange:6 Iced Tea:4 Tendon Meatballs:15] 3
Adding and changing are written exactly the same way. A key appears only once in a map, so writing to a key that already exists replaces it.
A key that isn't there: the zero value and comma-ok
Chicken Soup isn't on the price list. Before you look at the code, guess: does prices["Chicken Soup"] give an error, nil or 0?
fmt.Println(prices["Chicken Soup"]) // 0
price, found := prices["Chicken Soup"]
fmt.Println(price, found) // 0 false
price, found = prices["Tendon Meatballs"]
fmt.Println(price, found) // 15 true
- Reading a key that isn't there does not cause an error. You get the zero value of the value type:
0for int,""for string,falsefor bool. - The catch is that
0could also be a price that really is 0. To tell them apart, take two values at once. The second one (found, often namedok) istruewhen the key is there. This pattern is called comma-ok. - So for
m := map[string]int{"a": 1},val, ok := m["b"]makesfmt.Println(val, ok)print0 false. - A pattern you'll see a lot:
if _, ok := prices["Chicken Soup"]; !ok { fmt.Println("Chicken Soup is not on the menu") }.
range over a map: the order isn't fixed
for name, price := range prices {
fmt.Println(name, price)
}
Run it twice and the order can differ:
Tendon Meatballs 15
Iced Tea 4
Iced Orange 6
Iced Tea 4
Iced Orange 6
Tendon Meatballs 15
Go deliberately doesn't promise any order for range over a map, so don't rely on it. Need a fixed order? Sort the keys first: for _, name := range slices.Sorted(maps.Keys(prices)) (Go 1.23 and newer, with import "maps" and "slices").
Counting with a map
Because a key that isn't there yet reads as 0, counts[p]++ works for counting straight away, without filling anything in first:
orders := []string{"Tendon Meatballs", "Iced Tea", "Tendon Meatballs", "Chicken Noodles", "Tendon Meatballs", "Iced Tea"}
counts := make(map[string]int)
for _, p := range orders {
counts[p]++
}
fmt.Println(counts) // map[Chicken Noodles:1 Iced Tea:2 Tendon Meatballs:3]
fmt.Println(len(counts)) // 3
p |
counts[p] before |
after |
|---|---|---|
| Tendon Meatballs | 0 | 1 |
| Iced Tea | 0 | 1 |
| Tendon Meatballs | 1 | 2 |
| Chicken Noodles | 0 | 1 |
| Tendon Meatballs | 2 | 3 |
| Iced Tea | 1 | 2 |
Text separated by spaces can be counted the same way: split it into a slice first with strings.Split(text, " "), then range over the result. Don't forget import "strings"; without it Go refuses with undefined: strings. len(counts) gives the number of different keys.
A nil map: you can read it, not write it
var prices map[string]int // not made yet: nil
fmt.Println(prices["Tendon Meatballs"]) // 0, reading is safe
prices["Tendon Meatballs"] = 15 // panic
0
panic: assignment to entry in nil map
goroutine 1 [running]:
main.main()
/app/main.go:8 +0x85
exit status 2
var prices map[string]intonly declares the variable; the map itself doesn't exist yet (nil). Reading,lenandrangeare safe and come back empty, but writing panics.- Make it before you fill it:
prices := make(map[string]int)orprices := map[string]int{}.new(map[string]int)doesn't help, because it's only a pointer to a map that is still nil.
📌 Maps and goroutines
A built-in map isn't safe to write from several goroutines at once: Go stops the program with fatal error: concurrent map writes. How to make it safe comes in the Mutex & Sync lesson.
⚠️ Why does the map panic, or why is the number 0?
- Writing to a nil map.
var m map[string]intthenm["x"] = 1panics. Make it first withmakeor a literal. - Thinking 0 means the key isn't there. Use comma-ok:
price, ok := prices[k]. - Relying on the order of
range. Sort the keys when you need a fixed order. - Forgetting
import "strings"when usingstrings.Split.
TL;DR: map[string]int{"Tendon Meatballs": 15} stores pairs of a key and a value. m[k] reads, m[k] = v adds or replaces, delete(m, k) deletes, len(m) counts the pairs. A key that isn't there reads as the zero value (0), and v, ok := m[k] gives ok = false to tell them apart. The order of range isn't fixed, while fmt.Println prints the keys sorted. A nil map (var m map[string]int) can be read but panics when written, so make it first with make(map[string]int) or map[string]int{}. m[k]++ is the short way to count occurrences.
⚡ Keys and values
Write:
prices := map[string]int{
"Tendon Meatballs": 15,
"Chicken Noodles": 12,
"Iced Tea": 5,
}
fmt.Println(prices["Tendon Meatballs"]) // 15
Meaning: Give it the key, and the map hands you the value straight away. prices[k] = v adds or replaces, delete(prices, k) deletes.
⚡ A key that isn't there
Guess first: Chicken Soup isn't on the price list. Does prices["Chicken Soup"] give an error, nil or 0?
0, the zero value of the value type. To tell it apart from a price that really is 0, take two values: price, found := prices["Chicken Soup"] gives 0 false.
Meaning: This pattern is called comma-ok, and its second variable is often named ok.
⚡ Make it first, then fill it
Guess first: var prices map[string]int, then prices["Tendon Meatballs"] = 15. What happens?
A panic: assignment to entry in nil map. The map hasn't been made yet, so it's still nil. Reading it is safe, writing it is not.
Meaning: A map that is ready to fill is made with make(map[string]int) or the literal map[string]int{}.