Go uses the for keyword for every loop form: counted loops, condition-controlled loops, and range-based iteration over slices, arrays, and maps. section 3.5
Choose the form that matches the collection or control pattern:
- Use `for i := min; i < limit; i++` for counted iteration. section 3.5
- Use `for condition()` when the loop continues while a condition holds. section 3.5
- Use `for _, value := range mySlice` to iterate slice or array values without retaining the index. section 3.5
- Use `for key, value := range myMap`, `for _, value := range myMap`, or `for key := range myMap` to select the needed map components. section 3.5
Counting books with nested loops
A book-counting function ranges over each bookworm, then over that person's books. The unused outer index is discarded with `_`, and `count[book]++` increments each map entry; a missing entry contributes the uint zero value. section 3.2.1
Listing 3.12 bookworm.go: The booksCount() function
// booksCount registers all the books and their occurrences
// from the bookworms shelves.
func booksCount(bookworms []Bookworm) map[Book]uint {
count := make(map[Book]uint) #1
for _, bookworm := range bookworms { #2
for _, book := range bookworm.Books {
count[book]++ #3
}
}
return count
}
Inspect a complete `booksCount` implementation using nested range loops, a map accumulator, and an increment operation. section 3.2.1
