In Go programming, break
and continue
statements are essential tools for controlling the flow of loops. These statements allow developers to create more efficient and flexible code by manipulating loop execution.
The break
statement is used to exit a loop prematurely. When encountered, it immediately terminates the innermost loop and transfers control to the next statement after the loop.
for i := 0; i < 10; i++ {
if i == 5 {
break
}
fmt.Println(i)
}
fmt.Println("Loop terminated")
In this example, the loop will print numbers from 0 to 4 and then exit when i
equals 5.
The continue
statement skips the rest of the current iteration and moves to the next iteration of the loop. It's useful when you want to skip certain elements in a loop without terminating it entirely.
for i := 0; i < 5; i++ {
if i == 2 {
continue
}
fmt.Println(i)
}
This code will print numbers 0, 1, 3, and 4, skipping 2 due to the continue
statement.
When working with nested loops, break
and continue
affect only the innermost loop by default. However, Go provides labels to control outer loops as well.
outerLoop:
for i := 0; i < 3; i++ {
for j := 0; j < 3; j++ {
if i == 1 && j == 1 {
break outerLoop
}
fmt.Printf("%d %d\n", i, j)
}
}
In this example, the break
statement with the label outerLoop
will terminate both inner and outer loops when i
and j
are 1.
break
when you need to exit a loop early based on a condition.continue
to skip unnecessary iterations and improve performance.To further enhance your understanding of Go's control flow, explore these related topics:
Mastering break
and continue
statements will significantly improve your ability to write efficient and elegant Go code. Practice using these statements in various scenarios to become proficient in controlling loop execution.