// Chapter 28 example: range gives a copy of each struct. The first loop only // changes the copies. The second loop uses the position, and changes the slice. // Run with: go run exercises/28/02-range-copy.go package main import "fmt" type critter struct { name string energy int } func (c *critter) play() { c.energy = c.energy - 1 fmt.Printf("%s plays. Energy: %d\n", c.name, c.energy) } func main() { critters := []critter{ {name: "Spark", energy: 3}, {name: "Bolt", energy: 2}, } for _, c := range critters { c.play() } fmt.Println(critters) // [{Spark 3} {Bolt 2}] for i := range critters { critters[i].play() } fmt.Println(critters) // [{Spark 2} {Bolt 1}] }