liveBook · Manning

Generalized for

As explained in Learn Go with Pocket-Sized Projects

The for keyword introduces Go's looping construct for repeated or range-based execution.

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

How Learn Go with Pocket-Sized Projects covers it

How deep it goes
Explains common syntaxes, index selection, nested range loops, and map accumulation without descending into runtime internals.
Examples
Demonstrates bookworm shelves, book-frequency maps, nested traversal, map comparison, and table-driven tests.
What you can do after
Apply via Go to traverse collections, select indexes or values, accumulate results, and test loop-driven functions.
How it connects
Connects for loops with range, slices, arrays, maps, map keys, zero values, and table-driven testing.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Go with Pocket-Sized Projects. The section links point to the parts of the book it draws on.