Break and Continue Statements in Go
Learn Go through interactive, bite-sized lessons. Build scalable applications with modern concurrency.
Start Go Journey →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
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.
Example of Break Statement
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
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.
Example of Continue Statement
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.
Using Break and Continue in Nested Loops
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.
Best Practices
- Use
breakwhen you need to exit a loop early based on a condition. - Employ
continueto skip unnecessary iterations and improve performance. - Be cautious with labels in nested loops to maintain code readability.
- Consider refactoring complex loop logic into separate functions for better maintainability.
Related Concepts
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.