Mutating Maps

Insert or update an element in map m:

  1. m[key] = elem

Retrieve an element:

  1. elem = m[key]

Delete an element:

  1. delete(m, key)

Test that a key is present with a two-value assignment:

  1. elem, ok = m[key]

If key is in m, ok is true. If not, ok is false.

If key is not in the map, then elem is the zero value for the map's element type.

Note: If elem or ok have not yet been declared you could use a short declaration form:

  1. elem, ok := m[key]

mutating-maps.go

  1. package main
  2. import "fmt"
  3. func main() {
  4. m := make(map[string]int)
  5. m["Answer"] = 42
  6. fmt.Println("The value:", m["Answer"])
  7. m["Answer"] = 48
  8. fmt.Println("The value:", m["Answer"])
  9. delete(m, "Answer")
  10. fmt.Println("The value:", m["Answer"])
  11. v, ok := m["Answer"]
  12. fmt.Println("The value:", v, "Present?", ok)
  13. }