Continue and Break
Go provides two keywords to modify the flow of a loop from within its body: continue and break.
continue
The continue keyword stops the current iteration and immediately moves to the next one (evaluating the AFTER and CONDITION steps). It is often used as a guard clause to skip unnecessary processing.
for i := 0; i < 10; i++ {
if i % 2 == 0 {
continue // Skip even numbers
}
fmt.Println(i) // Only odd numbers are printed
}
break
The break keyword stops the loop entirely and exits the block.
for i := 0; i < 10; i++ {
if i == 5 {
break // Stop at 5
}
fmt.Println(i)
}
Clean Code
Using continue can help reduce indentation by handling “skip” conditions early, keeping the main logic of your loop at a shallower nesting level.