loop

202307071954
Status: #idea
Tags: Rust

loop

loop {
	println!("Infinite loop");
}

Returning values from loop

fn main() {
	let mut counter = 0;
	
	let result = loop {
		counter += 1;
		if counter == 10 {
			break counter * 2;
		}
	}
	
	println!("The value of result is {result}"); // 20
}

loop labels

Info

By default, break and continue affect the innermost loop

fn main() {
	// ...
	'counting_up: loop {
		loop {
			if condition_1 {
				break; // Breaks inner loop
			} else if condition_2 {
				break 'counting_up;
			} else if condition_3 {
				continue 'counting_up;
			}
		}
	}
}

References

  1. https://rust-book.cs.brown.edu/ch03-05-control-flow.html#repeating-code-with-loop
  2. Control Flow