Maps
A slice finds a value by its position, like prices[0]. But often you want to find a value by a name. What does an apple cost? What is the status of order 102? For this, Go has the map.
A map stores key-value pairs. The key is what you look up with, for example "apple". The value is what you get back, for example 3. Each key appears only once in a map.
package main
import "fmt"
func main() {
prices := map[string]int{
"apple": 3,
"bread": 5,
"milk": 2,
}
fmt.Println(prices["bread"])
prices["milk"] = 4
prices["tea"] = 6
fmt.Println(prices)
fmt.Println(len(prices))
}
Output:
5
map[apple:3 bread:5 milk:4 tea:6]
4
The type map[string]int names two types: the keys are strings and the values are ints. The part in curly braces is a map literal. It gives the starting pairs, with a colon between each key and its value.
The square brackets take a key, not a position. prices["milk"] = 4 replaces the old value 2, because the key milk already exists. prices["tea"] = 6 adds a new pair, because tea was not there. len gives the number of pairs. When you print a whole map with fmt.Println, the keys come out in sorted order.
Is the key there?
Reading a key that is not in the map is not an error. You get the zero value of the value type: 0 for an int, and an empty string for a string:
prices := map[string]int{"apple": 3, "milk": 4}
fmt.Println(prices["kiwi"])
Output:
0
That is a problem. Is kiwi free, or is it missing? To find out, read the key into two variables. The second one is a bool that tells you if the key was found:
price, ok := prices["kiwi"]
fmt.Println(price, ok)
price, ok = prices["apple"]
fmt.Println(price, ok)
Output:
0 false
3 true
This is called the comma-ok form. You will often see it inside an if, using the short statement before the condition from the If Statements lesson:
if p, ok := prices["milk"]; ok {
fmt.Println("milk costs", p)
}
Output:
milk costs 4
The variables p and ok exist only inside that if. This keeps the lookup and the check on one line.
Removing a pair
delete(map, key) removes a key and its value. Deleting a key that is not there does nothing:
delete(prices, "milk")
delete(prices, "kiwi")
fmt.Println(prices, len(prices))
Output:
map[apple:3] 1
Milk is gone, and one pair is left.
An empty map, and a nil map
To start with an empty map, use make or a literal with nothing in the braces:
stock := make(map[string]int)
stock["pens"] = 12
fmt.Println(stock)
colors := map[string]string{}
fmt.Println(colors, len(colors))
Output:
map[pens:12]
map[] 0
If you only declare a map with var, it has no storage yet. Its value is nil, which means "nothing". You can read from a nil map, but writing to it stops the program with a panic, a runtime error:
var stock map[string]int
fmt.Println(stock["pens"])
stock["pens"] = 12
Output:
0
panic: assignment to entry in nil map
The read printed 0, and then the write crashed. Always create a map with make or a literal before you add pairs to it.
In the exercise, look up an order ID with the comma-ok form, then delete it and print how many orders are left.