Today, we are going to learn about break and continue, which are control tools used in loops in Go. The break command allows us to exit a loop early, while continue facilitates skipping unnecessary iterations. Let's dive in!
You can liken the break command to the moment when the music stops in a game of musical chairs, prompting you to leave the loop. It ends the loop, irrespective of the original condition of the loop.
Here is a quick example:
Our loop operates on numbers from 0 through 6 and breaks when it reaches 7, thereby exiting early and skipping all remaining iterations.
The continue keyword in Go can be compared to bypassing a boring view during a walk. It disregards the current loop iteration and moves ahead to the next one.
Here is an example:
Our output confirms that we admire all buildings except numbers 4 and 7, which our continue statement skips.
Nested loops are loops within loops. In these loops, break and continue work in distinct ways. It's important to understand that both break and continue will exit or skip only their respective inner loop, not affecting the outer loop. Let's illustrate this with a couple of examples.
Consider a nested loop running on a 5x5 grid.
In this context, break ends the inner loop when i and j both equal 3. Thus, when i becomes 3, the inner loop runs only up to j = 2 and then terminates. However, the outer loop continues until i = 5.
Meanwhile, let's introduce 'continue' in a similar setup.
When continue encounters the i = 3, j = 3 condition, it skips the rest of the code inside its loop and swiftly moves to the next iteration. In this case, it means we omit printing j when both i and j are equal to 3.
