Concept Flow - Loop labels
Start Outer Loop 'outer'
Start Inner Loop 'inner'
Check Condition in Inner
Break 'outer'
Exit Outer
Repeat Outer
The flow shows how labeled loops let you break or continue specific loops, even nested ones.
fn main() {
'outer: for i in 1..=3 {
'inner: for j in 1..=3 {
if i == 2 && j == 2 {
break 'outer;
}
println!("i={}, j={}", i, j);
}
}
}| Step | i | j | Condition (i==2 && j==2) | Action | Output |
|---|---|---|---|---|---|
| 1 | 1 | 1 | false | Print i=1, j=1 | i=1, j=1 |
| 2 | 1 | 2 | false | Print i=1, j=2 | i=1, j=2 |
| 3 | 1 | 3 | false | Print i=1, j=3 | i=1, j=3 |
| 4 | 2 | 1 | false | Print i=2, j=1 | i=2, j=1 |
| 5 | 2 | 2 | true | Break 'outer' loop | |
| 6 | - | - | - | Exit all loops |
| Variable | Start | After 1 | After 2 | After 3 | After 4 | After 5 | Final |
|---|---|---|---|---|---|---|---|
| i | - | 1 | 1 | 1 | 2 | 2 | - |
| j | - | 1 | 2 | 3 | 1 | 2 | - |
Loop labels in Rust let you name loops. Use 'label: for ...' to name a loop. Use break 'label or continue 'label to control specific loops. This helps manage nested loops clearly. Without labels, break/continue affect only innermost loop.
loop labels in Rust?'label: before the loop keyword.'label: loop {}.fn main() {
let mut count = 0;
'outer: loop {
println!("Outer loop: {}", count);
let mut inner_count = 10;
loop {
println!(" Inner loop: {}", inner_count);
if inner_count == 9 {
break 'outer;
}
inner_count -= 1;
}
count += 1;
}
println!("Done");
}fn main() {
'start: loop {
loop {
break start;
}
}
}break 'start;.break start; missing the apostrophe before the label name, causing a syntax error.'outer and 'inner, how can you skip the current iteration of the outer loop from inside the inner loop?continue 'outer; skips the current iteration of the loop labeled 'outer, jumping to its next iteration.break exits the loop, while continue skips to the next iteration. To skip outer loop iteration from inner loop, use continue 'outer;.Pass the test and this pattern moves unknown