What if you could instantly stop any loop inside another without messy tricks?
Why Loop labels in Rust? - Purpose & Use Cases
Imagine you have two loops inside each other, like two spinning wheels. You want to stop the outer wheel from inside the inner one. Without a clear way to say which wheel to stop, you get confused and stuck.
Stopping just the inner loop is easy, but stopping the outer loop from inside the inner one means you must add extra checks or flags. This makes your code messy, hard to read, and easy to make mistakes.
Loop labels let you name your loops. Then, from inside any loop, you can say exactly which loop to break or continue. This keeps your code clean and your intentions clear.
for i in 0..5 { for j in 0..5 { if i + j > 5 { break; // only breaks inner loop } } }
'outer: for i in 0..5 {
for j in 0..5 {
if i + j > 5 {
break 'outer; // breaks outer loop directly
}
}
}You can control exactly which loop to stop or continue, making complex nested loops easy and safe to manage.
When searching in a grid for a special item, you want to stop searching completely as soon as you find it, even if you are deep inside nested loops.
Nested loops can be confusing without clear control.
Loop labels let you name loops for precise control.
This makes your code cleaner and easier to understand.