Loops
-
Rust has three kinds of loops:
loop
- Infinite Loop, usesbreak
andcontinue
while
- Breaks when the condition doesn't meet.for
- Faster and easier to use for iterators and classical for loops.
-
Simple Infinite Loop:
#![allow(unused)] fn main() { loop { // Do something iteratively } }
-
Named Loop
#![allow(unused)] fn main() { 'outer:loop { loop { break 'outer; } } }
-
Named Loop with different breaks:
#![allow(unused)] fn main() { 'oulter_loop: loop { loop { if condition { break 'oulter_loop; // Breaks Outer Loop } if some_other_condition { break; // Breaks Inner Loop } } } }
-
Returning values in loops:
fn main() { let mut counter = 0; let result = loop { counter += 1; if counter == 10 { break counter * 2; } }; println!("The result is {}", result); }
-
The
while
loop:fn main() { let mut number = 3; // Prevents the use of break, by including the condition with while while number != 0 { println!("{}!", number); number -= 1; } println!("LIFTOFF!!!"); }
-
The
for
loop:#![allow(unused)] fn main() { // Last item in exclusive, or 0..10 === 0..=9 for x in 0..10 { println!("{}", x); // x: i32 } }
-
The
for
loop for iterator:fn main() { let a = [10, 20, 30, 40, 50]; for element in a { println!("the value is: {}", element); } }
-
A for loop for iterating characters in String
#![allow(unused)] fn main() { for c in name.chars() { // c variable stores one charater per iteration } }
-
Enumeration
#![allow(unused)] fn main() { for (i, v) in request.chars().enumerate() { // i is index, v is variable } }
-
The
for
loop in reverse:fn main() { for number in (1..4).rev() { println!("{}!", number); } println!("LIFTOFF!!!"); } // Output: // 3! // 2! // 1! // LIFTOFF!!!