What if you could instantly stop the right loop without messy code?
Why Labelled break and continue in Go? - Purpose & Use Cases
Imagine you are cooking multiple dishes at once, and you need to stop cooking one dish immediately when a problem happens, but continue with the others. Without a clear way to say "stop this dish" and "keep cooking the rest," you might get confused or waste time.
Using only simple break or continue statements inside nested loops is like shouting "stop!" without saying which dish to stop. It can only stop the innermost loop, making it hard to control outer loops. This leads to messy code and mistakes.
Labelled break and continue let you name your loops, so you can clearly say "stop this specific loop" or "skip to the next round of this loop." This makes your code cleaner and easier to understand, like having clear instructions for each dish.
for i := 0; i < 3; i++ { for j := 0; j < 3; j++ { if someCondition { break } } }
OuterLoop: for i := 0; i < 3; i++ { for j := 0; j < 3; j++ { if someCondition { break OuterLoop } } }
It enables precise control over complex nested loops, making your programs easier to read and less error-prone.
When searching for a specific item in a grid, you can immediately stop all searching once found, instead of checking every cell unnecessarily.
Labelled break and continue let you control which loop to affect.
They prevent confusion in nested loops.
They make your code cleaner and more efficient.