go · level 2 · unit 1 · lesson 2
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Maps grow, change and shrink while your program runs.
To add a key or change its value, assign to it: stock["apples"] = 12. A new key makes the map grow, and a key that is already there gets its old value replaced. removes a key, and len(stock) counts the keys.
Ask for a key that is not there and Go does not crash. It hands back the for the type: 0 for an int, "" for a string and false for a bool.
To start with an empty map, use : stock := make(map[string]int). A map declared with var stock map[string]int was never made, and storing anything in it causes a panic.
package main
import "fmt"
func main() {
stock := make(map[string]int)
stock["apples"] = 12
stock["pears"] = 4
stock["apples"] = 10
delete(stock, "pears")
fmt.Println(stock, len(stock))
fmt.Println(stock["plums"])
} Deleting a key that is not there does nothing, so delete is always safe to call.
guess first
Lunch vote! What does the map hold now?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
package main
import "fmt"
func main() {
votes := map[string]int{"pizza": 3, "pasta": 2}
votes["pasta"] = votes["pasta"] + 2
votes["soup"] = votes["soup"] + 1
fmt.Println(votes)
}
your turn
Your turn. Sort out the lost property box.
On line 5, add a lost item of your own and the name of its owner. On line 6, delete either umbrella or scarf, because its owner came to collect it. Then run it.
output
press run to see what happens
fix it
The scoreboard crashes. Can you fix it?
output
press run to see what happens
- The program panics on line 5, the first time it stores something. Was the map ever made?
- A map declared with
varis not ready to hold anything. You needmaketo build it. - Change line 4 to scores := make(map[string]int), then run.
nailed it
your maps can grow and shrink. :D
m[key] = valueadds a key or replaces its value.deleteremoves a key, andlencounts the keys.- A missing key gives the zero value, such as
0or"".
new words in your collection
- zero value
- make
- delete
This lesson isn’t saved. A free account remembers every lesson you finish.