Skip to content

Go for loop patterns

Go features a single looping construct, the for loop, which supports multiple iteration patterns^[400-devops-09-scripting-language-golang-introduction-readme.md]. Unlike some languages that provide distinct while or loop keywords, Go uses the for statement to handle all iteration scenarios^[400-devops-09-scripting-language-golang-introduction-readme.md].

Loop variations

The language supports three primary patterns for controlling loop execution^[400-devops-09-scripting-language-golang-introduction-readme.md]:

  • Infinite loop: A conditional-less loop that executes forever unless explicitly terminated.
    for {
      // code runs forever
      break // exit loop
    }
    
  • Conditional loop: A traditional "while-style" loop that runs while a condition remains true.^[400-devops-09-scripting-language-golang-introduction-readme.md]
  • For clause: A C-style loop with an init statement, condition, and post statement (e.g., for x := 0; x < 10; x++)^[400-devops-09-scripting-language-golang-introduction-readme.md].

Range-based iteration

The range keyword allows for clean iteration over collections such as arrays, slices, or maps^[400-devops-09-scripting-language-golang-introduction-readme.md]. This pattern returns two values: the index (or key) and the element (or value).

  • Iterating elements: If the index is not required, it can be discarded by using an underscore (_) as a placeholder^[400-devops-09-scripting-language-golang-introduction-readme.md].
  • Accessing data: Within the loop body, the current element can be accessed either via the range-provided variable or manually via index if the collection is an array or slice^[400-devops-09-scripting-language-golang-introduction-readme.md].
  • [[Go slices]]
  • [[Go arrays]]
  • [[Go structs]]

Sources

^[400-devops-09-scripting-language-golang-introduction-readme.md]