Loop Keyword in Rust Programming

Rust ProgrammingServer Side ProgrammingProgramming

Rust provides a loop keyword that allows us to run an infinite loop. The infinite loop indicated by the help of the loop keyword can be broken by the use of the break keyword. Also, we can exit an iteration and continue the infinite loop with the help of the continue keyword.

Example

Consider the example shown below −

 Live Demo

fn main() {
   let mut count = 0u32;
   println!("Infinite loop begins!!");
   // Infinite loop
   loop {
      count += 1;
      if count == 4 {
         println!("four");
         continue;
      }
      println!("{}", count);
      if count == 7 {
         println!("OK, that's enough!!");
         break;
      }
   }
}

Output

Infinite loop begins!!
1
2
3
four
5
6
7
OK, that's enough!!

Nesting and Labels

Rust also provides us with a unique feature with which we can break or continue the outer loop execution from inside the nested loops. In order to do that, we just need to‘label’ the loops.

Example

Consider the example shown below −

 Live Demo

#![allow(unreachable_code)]

fn main() {
   'outerloop: loop {
      println!("Entered - outer loop");
      'innerloop: loop {
         println!("Entered - inner loop");
         // This breaks the outer loop
         break 'outerloop;
      }
      println!("This line will never be printed");
   }
   println!("Exited the outer loop");
}

Output

Entered - outer loop
Entered - inner loop
Exited the outer loop
raja
Published on 03-Apr-2021 13:05:00
Advertisements