Go Loops

Basic for Loop

Go has only one looping construct: for. It's flexible enough to behave like a C-style loop.

Basic Structure:

for initialization; condition; update {
    // code block
}

Parentheses, (), are NOT used in for loops in Go, it will cause a syntax error.

Loading...
Output:

While-like for Loop

Go does not have a dedicated while loop like some other languages. Instead, it uses the for loop in different forms. When you omit the initialization and post statements, for behaves exactly like a while loop.

Basic Structure:

for condition {
    // code block
}

This pattern is commonly used for looping until a condition becomes false:

Loading...
Output:

This form is clean, readable, and idiomatic in Go for situations where you need a loop that runs while a condition holds.

Infinite Loop

Use for with no condition to create an infinite loop:

for {
    fmt.Println("This runs forever")
}

break and continue

Use break to exit a loop and continue to skip an iteration.

Loading...
Output:

Range-based Looping

Use range to loop over arrays, slices, strings, maps, or channels:

Loading...
Output:

If you only need the value, use _ to ignore the index:

Loading...
Output:

Nested Loops

Use nested for loops for grid-like data:

Loading...
Output:

Need Help?

Ask the AI if you need help understanding or want to dive deeper in any topic