Using loop labels

Rust allows us to label our loops. This can be very useful, for example with nested loops. These labels act as symbolic names for the loop and as we have a name for the loop, we can instruct the application to perform a task on that name.

Consider the following simple example:

// 04/looplabels/src/main.rsfn main()  
{ 
    'outer_loop: for x in 0..10  
    { 
        'inner_loop: for y in 0..10  
        { 
            if x % 2 == 0 { continue 'outer_loop; }  
            if y % 2 == 0 { continue 'inner_loop; } 
            println!("x: {}, y: {}", x, y); 
        } 
    } 
} 

What will this code do?

Here, x % 2 == 0 (or y % 2 == 0) means that if a variable divided by two returns no remainder, then the condition is met and it executes the code in the braces. When x % 2 == 0, or when the value of the loop is ...

Get Learning Rust now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.