liveBook · Manning

Loop

As explained in Learn Go with Pocket-Sized Projects

A for loop is Go's looping construct for repeatedly executing a block with optional initialization, condition, and post-iteration expressions.

Go uses one loop keyword, for, with several forms: a three-part loop for counted iteration, a condition-only loop, or an infinite loop. section 3.5 section 3.1.4

Choose the form that matches the collection or stopping condition:

  • Use `for i := 0; i < limit; i++` for indexed, counted work. section 3.1.4
  • Use `for condition()` when iteration continues while a condition remains true. section 3.5
  • Use `for index, value := range slice` or `range map` to visit collection elements, indexes, keys, and values. section 3.5
  • Replace an unused index or value with `_`; use `for index := range slice` when only indexes are needed. section 3.5

Display books with range

A `displayBooks` function ranges over a slice and prints each title and author: `for _, book := range books { fmt.Println("-", book.Title, "by", book.Author) }`. The resulting function can be called from `main` and checked with an example test. section 3.3

Listing 3.19 bookworms.go: displayBooks
// displayBooks prints out the titles and authors of a list of books
func displayBooks(books []Book) {
    for _, book := range books {
        fmt.Println("-", book.Title, "by", book.Author)
    }
}

Inspect the complete `displayBooks` implementation, including range iteration and formatted output. section 3.3

How Learn Go with Pocket-Sized Projects covers it

How deep it goes
Defines counted, conditional, infinite, and range forms, including index and value selection, without deeper runtime internals.
Examples
Demonstrates book-list printing, bookworm comparison helpers, and map-driven test cases.
What you can do after
Apply it via Go syntax to repeat work, traverse collections, print results, and compare structured test data.
How it connects
Ties for loops to slices, arrays, maps, range iteration, formatted output, and testing.

Also explained in

Compare how 27 books explain loop →

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.