iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

for Loops

Go has exactly one loop keyword: for. It plays all the parts — classic three-clause loop, while-loop, infinite loop, and range over collections.

Every shape of for

EXAMPLE
package main

import "fmt"

func main() {
    // 1) Classic three-clause
    for i := 0; i < 5; i++ {
        fmt.Println(i)
    }

    // 2) While-loop — drop the init + post
    n := 0
    for n < 3 {
        n++
    }

    // 3) Infinite + break
    for {
        if done() { break }
        work()
    }

    // 4) Range over a slice — index + value
    nums := []int{10, 20, 30}
    for i, v := range nums {
        fmt.Println(i, v)
    }

    // 5) Range over a map — key + value (order NOT guaranteed)
    ages := map[string]int{"Ada": 36, "Bo": 28}
    for name, age := range ages {
        fmt.Println(name, age)
    }

    // 6) Range over a string — runes, not bytes
    s := "héllo"
    for i, r := range s {
        fmt.Printf("%d %c\n", i, r)
    }

    // 7) Range over a channel — until it's closed
    ch := make(chan int, 3)
    ch <- 1; ch <- 2; ch <- 3; close(ch)
    for v := range ch {
        fmt.Println(v)
    }

    // 8) Range over an integer (Go 1.22+)
    for i := range 5 {
        fmt.Println(i)   // 0, 1, 2, 3, 4
    }

    // 9) Labels — break / continue an outer loop
outer:
    for i := 0; i < 5; i++ {
        for j := 0; j < 5; j++ {
            if i == j { continue outer }
            if i+j > 5 { break outer }
        }
    }
}

func done() bool { return false }
func work()      {}

Why it matters

In Go 1.22+ each loop iteration gets its own per-iteration variables — the famous closure-over-loop-var bug is fixed. Old code with goroutines + range needs no v := v workaround anymore.

Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.

Example

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

for i, v := range []string{"a","b","c"} {
    fmt.Println(i, v)
}
Try it Yourself »

Discussion

Loading…