Rust: Loops

There are three main types of loops in Rust.

  1. For loop
  2. While loop
  3. Loop - infinite loop

Example: For Loop


	fn main() {
		for x in 0..4 {
			println!("{}", x); 
		}
	}
	

Output:

  0
  1
  2
  3


Example: while Loop


	fn main() {
		let mut number = 3;
		while number != 0 {
			println!("x = {}", number);
			number = number - 1;
		}
	}
	

Output:

  x = 3
  x = 2
  x = 1


Example: Loop (infinite) in Rust


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

Output:

  0
  1
  2
  3

The break command must be used in the loop above to end the loop.