Apps Artificial Intelligence CSS DevOps Go JavaScript Laravel Linux MongoDB MySQL PHP Python Rust Svelte Vue

Loops in Go: A Practical Guide with Examples

1 min read .
Loops in Go: A Practical Guide with Examples

Go has only one looping keyword: for. That can look unusual if you come from a language with separate for, while, and do-while constructs, but Go’s for is flexible enough to cover the common looping patterns.

1. Basic for Loop

for i := 0; i < 5; i++ {
    fmt.Println(i)
}

This is similar to a traditional loop in C, Java, or JavaScript: initialize a counter, continue while the condition is true, and run the post statement after each iteration.

2. Use for Like a while Loop

Omit the initialization and post statement:

i := 0
for i < 5 {
    fmt.Println(i)
    i++
}

3. Infinite Loops

A for statement without a condition runs indefinitely until something exits the loop:

i := 0
for {
    fmt.Println(i)
    i++
    if i >= 5 {
        break
    }
}

4. Iterate over Collections with range

Array or slice:

numbers := []int{1, 2, 3}
for index, value := range numbers {
    fmt.Printf("%d: %d\n", index, value)
}

Map:

people := map[string]int{"Alice": 30, "Bob": 25}
for key, value := range people {
    fmt.Printf("%s: %d\n", key, value)
}

Map iteration order is not guaranteed, so do not depend on keys being returned in a particular sequence.

String:

message := "Hi"
for index, r := range message {
    fmt.Printf("%d: %c\n", index, r)
}

When ranging over a string, Go iterates over Unicode code points (rune values). The index is the byte offset, not necessarily a character count.

5. Nested Loops

for i := 1; i <= 3; i++ {
    for j := 1; j <= 3; j++ {
        fmt.Printf("i=%d, j=%d\n", i, j)
    }
}

6. Control Loop Execution

Use:

  • break to leave the current loop.
  • continue to skip directly to the next iteration.
for i := 0; i < 10; i++ {
    if i%2 == 0 {
        continue
    }
    if i > 7 {
        break
    }
    fmt.Println(i)
}

Conclusion

Although Go has only one looping construct, it handles counted loops, condition-based loops, infinite loops, and iteration over arrays, slices, maps, strings, and channels. Learning the different forms of for is enough to cover nearly every ordinary iteration task in Go.

Related Posts

chevron-up