×

go · level 2 · unit 1 · lesson 2

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. 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.