// Chapter 28 example: changing a struct held in a map, the two ways that work. // Run with: go run exercises/28/05-map-of-structs.go package main import "fmt" type critter struct { name string energy int } func main() { // A map of structs: copy out, change the copy, put it back. team := map[string]critter{ "spark": {name: "Spark", energy: 3}, } c := team["spark"] c.energy = 2 team["spark"] = c fmt.Println(team["spark"].energy) // 2 // A map of pointers: change the critter through the pointer. pets := map[string]*critter{ "bolt": {name: "Bolt", energy: 2}, } pets["bolt"].energy = 1 fmt.Println(pets["bolt"].energy) // 1 // A missing key in a map of pointers gives nil, so check with ok first. pet, ok := pets["nova"] if !ok { fmt.Println("No critter called nova.") return } fmt.Println(pet.energy) }