Loop Labels
Part of the Fundamentals section of Coddy's Rust journey — lesson 42 of 75.
Labels in Rust help you break or continue specific loops when they're nested. Add 'label: before a loop to label it.
For example:
'outer: for i in 1..=3 {
'inner: for j in 1..=3 {
if i * j > 5 {
break 'outer;
// This will break the outer loop
}
println!("({}, {})", i, j);
}
}
In this example, we have two nested loops labeled 'outer and 'inner. When the product of i and j is greater than 5, the break 'outer; statement is executed, which exits the outer loop. The output of this code will be:
(1, 1)
(1, 2)
(1, 3)
(2, 1)
(2, 2)Similarly, you can use continue 'label; to continue to the next iteration of the specified loop. For example:
'outer: for i in 1..=3 {
'inner: for j in 1..=3 {
if i == j {
continue 'outer;
// This will continue the outer loop
}
println!("({}, {})", i, j);
}
}In this case, when i is equal to j, the continue 'outer; statement is executed, which skips the rest of the inner loop and continues with the next iteration of the outer loop. The output will be:
(2, 1)
(3, 1)
(3, 2)Challenge
BeginnerWrite a Rust program that uses labeled loops to find the first pair of numbers (i, j) such that their sum is greater than 10 and their product is a multiple of 12 (The product is divided by 12 without reminder). The program should iterate through i from 1 to 20 and j from 1 to 20.
When you find the pair, print it in the format (i, j) and break out of the outer loop.
Cheat sheet
Labels in Rust help you break or continue specific loops when they're nested. Add 'label: before a loop to label it.
Use break 'label; to exit a specific labeled loop:
'outer: for i in 1..=3 {
'inner: for j in 1..=3 {
if i * j > 5 {
break 'outer; // Breaks the outer loop
}
println!("({}, {})", i, j);
}
}Use continue 'label; to continue to the next iteration of a specific labeled loop:
'outer: for i in 1..=3 {
'inner: for j in 1..=3 {
if i == j {
continue 'outer; // Continues the outer loop
}
println!("({}, {})", i, j);
}
}Try it yourself
fn main() {
'outer: for i in 1..=20 {
for j in 1..=20 {
// Your logic here
break 'outer;
}
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorArithmetic ShortcutsComparison OperatorsString Comparison5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 33Variables Part 2
Type DeclarationNaming ConventionsType InferenceRecap - Initialize VariablesType Casting9Loops
For Over SeriesWhile LoopBreakContinueNested LoopLoop LabelsInfinite LoopRecap - Dynamic Input