Loop

Used to repeat a block of code over and over again. For example, the below will print "Hello world" again and again, forever.

   loop {
      println!("Hello world");
   }

Breaking out of a loop

You can terminate a loop with the break keyword.

  fn main() {
    let mut retries = 0;
    loop {
      if retries == 3 {
        break;
      }
     
      retries += 1;
      println!("{} retry attempts", retries);
    }
    println!("Done");
  }

You can use break to return a value from a loop as follows:

  fn main() {
    let mut retries = 0;
    let result  = loop {
      if retries == 3 {
        break retries;
      }
     
      retries += 1;
      println!("{} retry attempts", retries);
    };
    
    println!("Done. Result is {result}");
  }

Continuing a loop

You can use the continue keyword to continue with the next iteration of a loop i.e. skipping everything below the continue keyword in the block. In the example below, we skip the remaining part of the loop if the value of counter is not a multiple of 3 or 5. We break out of the loop when counter is greater than 30.

fn main() {

   let mut counter = 1;
   loop {
   
     counter += 1;
     if counter % 3 != 0 || counter % 5 != 0 {
        continue;
     }
     println!("{counter} is a multiple of 3 and 5");
     
     if counter > 30 {
        break;
     }
   }
}

Nested loops

If you have loops within loops, note that break and continue, apply to the innermost loop. However, you can use loop labels to indicate which loop you would like a break or continue to apply to. The example below demonstrates usage of break with loop labels.

fn main() {

   let mut counter = 0;

   'outer: loop {
      loop {
        counter += 1;
        if counter % 3 == 0 && counter % 5 == 0 {
           break 'outer;
        }
        println!("{counter} is not a multiple of 3 and 5");
      }
   }
   println!("{counter} is a multiple of 3 and 5");
}

While loops

fn main() {
    
  let mut counter = 10;  
  while counter > 0 {
     println!("{counter}");
     counter -= 1;
  }
  
  println!("Lift off");
}

For loops

Typically, you'd use for iterating a collection. For example,

fn main() {
   for number in 1..= 10 {
     println!("{number}");
   }   
   println!("Done");
}