On this page
article
Loop Labels
Loop Labels
What Is a Loop Label? A loop label assigns an identifier to a loop.
Syntax Write a label and colon before the loop.

- Example The code below prints the multiplication table of 1 to 5 except 3. See how specifying a loop label helps you to skip the table of 3.
fn main() {
'outer:for i in 1..5 { //outer loop
println!("Muliplication Table : {}", i);
'inner:for j in 1..5 { // inner loop
if i == 3 { continue 'outer; } // Continues the loop over `i`.
if j == 2 { continue 'inner; } // Continues the loop over `j`.
println!("{} * {} = {}", i, j, i * j);
}
}
}
output:
Muliplication Table : 1
1 * 1 = 1
1 * 3 = 3
1 * 4 = 4
Muliplication Table : 2
2 * 1 = 2
2 * 3 = 6
2 * 4 = 8
Muliplication Table : 3
Muliplication Table : 4
4 * 1 = 4
4 * 3 = 12
4 * 4 = 16
Explanation
Outer for Loop
- A for loop is defined on line
2. - The loop has a label outer . It takes i as an iterator that iterates over values from
1to4.
- A for loop is defined on line
Inner for Loop
- A for loop is defined on line
3 - The loop has a label inner. It takes j as an iterator that iterates over values from
1to5. - For each i the inner loop iterate j times and prints the product
i * j. - When the outer loop increments
ito3and the inner loop starts from j = 1, the conditioni == 3is found to be true and the continue ‘outer statement causes execution to be transferred to the next iteration of the outer loop on line2. The variableiis incremented to4and the execution continues. - When the value of j increments to
2, then the 2nd iteration of the inner loop gets skipped and continue ‘inner causes the execution to be transferred to the next iteration of the inner loop on line4. The variable j is incremented to3and the execution continues.
i j output
11
2
3
4
1 * 1 = 1
1 * 3 = 3
1 * 4 = 42 1
2
3
42 * 1 = 2
2 * 3 = 6
2 * 4 = 83 4 1
2
3
44 * 1 = 4
4 * 3 = 12
4 * 4 = 16- A for loop is defined on line
Last updated 25 Jan 2024, 05:11 +0530 .