go · level 2 · unit 1 · lesson 3
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
The form tells you whether a key is there.
A missing key gives the zero value, but sometimes zero is a real answer. If stock["pears"] gives 0, are the pears sold out, or does the shop not sell pears at all?
Catch a second value to find out: count, ok := stock["pears"]. ok is a bool that is true only when the key is in the map. Programmers call this the comma ok form.
It often goes inside an if, as a before the condition: if count, ok := stock["pears"]; ok {. The semicolon separates the two parts, and count can only be used inside that if and its else.
package main
import "fmt"
func main() {
stock := map[string]int{"apples": 12, "pears": 0}
count, ok := stock["pears"]
fmt.Println(count, ok)
count, ok = stock["plums"]
fmt.Println(count, ok)
} The name ok is only a habit, but every Go programmer recognises it at a glance.
guess first
Is Goldie booked into the pet hotel? Guess first.
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
package main
import "fmt"
func main() {
rooms := map[string]int{"Rex": 4, "Tibbles": 7}
if room, ok := rooms["Goldie"]; ok {
fmt.Println("Goldie is in room", room)
} else {
fmt.Println("No room booked for Goldie")
}
}
your turn
Your turn. Book your pet into the hotel.
On line 5, book a pet of your own into a room: type its name and a whole-number room. On line 6, look up the same name, spelled exactly the same, and run it.
output
press run to see what happens
fix it
The shop sells pears, but they are sold out. Fix the check!
output
press run to see what happens
- pears is in the map, but its value is 0. What does the
!=check on line 5 really ask? - Checking the value cannot tell a stored 0 from a missing key. You need the comma ok form.
- Change line 5 to if _, ok := stock["pears"]; ok { and run.
nailed it
you can tell missing from zero. :D
value, ok := m[key]says whether the key is there.okistrueonly when the key was found.- A short statement can come before an
ifcondition, after a semicolon.
new words in your collection
- comma ok
- short statement
This lesson isn’t saved. A free account remembers every lesson you finish.