Go has only one looping construct: for. It's flexible enough to behave like a C-style loop.
for initialization; condition; update {
// code block
}Parentheses, (), are NOT used in for loops in Go, it will cause a syntax error.
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.
for condition {
// code block
}This pattern is commonly used for looping until a condition becomes false:
This form is clean, readable, and idiomatic in Go for situations where you need a loop that runs while a condition holds.
Use for with no condition to create an infinite loop:
for {
fmt.Println("This runs forever")
}Use break to exit a loop and continue to skip an iteration.
Use range to loop over arrays, slices, strings, maps, or channels:
If you only need the value, use _ to ignore the index:
Use nested for loops for grid-like data:
Ask the AI if you need help understanding or want to dive deeper in any topic