Skip to content

Go loop constructs

Go provides a single looping construct, the for loop, which can be utilized in several different ways to handle iteration requirements^[400-devops__09-Scripting-Language__golang__introduction__readme.md].

Basic forms

The most common form is the C-style for loop, used to iterate a specific number of times.^[400-devops__09-Scripting-Language__golang__introduction__readme.md]

for x := 0; x < 10; x++ {
    fmt.Println(customers[x])
}

Go also supports an infinite loop that runs forever unless explicitly terminated^[400-devops__09-Scripting-Language__golang__introduction__readme.md].

for {
    // any code in here will run forever
    fmt.Println("Infinite Loop 1")
    time.Sleep(time.Second)

    // unless we break out the loop like this
    break
}

Iterating over collections

To iterate over collections, lists, or arrays (such as slices), the for loop is combined with the range keyword^[400-devops__09-Scripting-Language__golang__introduction__readme.md].

for x, customer := range customers {
    fmt.Println(customer)
}

When using range, the first variable returns the index, and the second returns the value. If the index is not required, it can be discarded by replacing it with an underscore (_)^[400-devops__09-Scripting-Language__golang__introduction__readme.md].

for _, customer := range customers {
    fmt.Println(customer)
}
  • [[Slices]]
  • [[Structs]]
  • [[Control Flows]]

Sources

  • 400-devops__09-Scripting-Language__golang__introduction__readme.md