In this tutorial you will learn about the Rust Continue Statement and its application with practical example.
Rust Continue Statement
In Rust, the continue statement gives you way to skip over the current iteration of any loop. When a continue statement is encountered in the loop, the rest of statements in the loop body for current iteration and returns the program execution to the very first statement in the loop body. It does not terminates the loop rather continues with the next iteration.
Rust Continue Statement Flow Diagram
Syntax:-
1 |
continue; |
Example:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
fn main() { println!("W3Adda Rust continue statement."); for ctr in 1..10 { if ctr == 5 { println!("5 is skipped"); ; } println!("Number is {}",ctr); } println!("Out of loop"); } |
When we run the above Rust program, we will see following output –
Output:-
As you can see when ctr == 5, continue statement is executed which causes the current iteration to end and the control moves on to the next iteration.
Rust Labeled Continue Statement
In Rust, sometimes you may encounter situations where you have nested loops, in such case you are required to specify the loop which one your continue
statement is applicable for. The standard unlabeled
continue
statement is applicable for the nearest enclosing loop. In Rust, there is another form of continue
(labeled continue) statement is used to continue outer loop. In such cases, the loops must be annotated with some ‘label, which is passed to the continue statement.
Example:-
1 2 3 4 5 6 7 8 9 10 11 12 |
fn main() { println!("W3Adda Rust Labeled continue statement."); 'outer: for x in 0..10 { 'inner: for y in 0..5 { if x % 2 == 0 { continue 'outer; } // continues the loop over x if y % 2 == 0 { continue 'inner; } // continues the loop over y println!("x: {}, y: {}", x, y); } } } |
Output:-