maps_forrange2.go 530 B

123456789101112131415161718192021
  1. package main
  2. import "fmt"
  3. func main() {
  4. // Version A:
  5. items := make([]map[int]int, 5)
  6. for i := range items {
  7. items[i] = make(map[int]int, 1)
  8. items[i][1] = 2
  9. }
  10. fmt.Printf("Version A: Value of items: %v\n", items)
  11. // Version B: NOT GOOD!
  12. items2 := make([]map[int]int, 5)
  13. for _, item := range items2 {
  14. item = make(map[int]int, 1) // item is only a copy of the slice element.
  15. item[1] = 2 // This 'item' will be lost on the next iteration.
  16. }
  17. fmt.Printf("Version B: Value of items: %v\n", items2)
  18. }