break and continue

If you want to exit a loop early, use break, if you want to immediately start the next iteration use continue. Both continue and break can optionally take a label argument which is used to break out of nested loops:

  1. fn main() {
  2. let v = vec![10, 20, 30];
  3. let mut iter = v.into_iter();
  4. 'outer: while let Some(x) = iter.next() {
  5. println!("x: {x}");
  6. let mut i = 0;
  7. while i < x {
  8. println!("x: {x}, i: {i}");
  9. i += 1;
  10. if i == 3 {
  11. break 'outer;
  12. }
  13. }
  14. }
  15. }

In this case we break the outer loop after 3 iterations of the inner loop.