rust / beginner
Snippet
Looping with for, while, and loop
Rust provides three looping constructs. The `for` loop iterates over collections. The `while` loop runs as long as a condition is true. The `loop` keyword creates an infinite loop that must be explicitly broken. The `loop` can also return a value via `break`, which is useful for pattern matching inside loops.
snippet.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
fn main() {let numbers = [1, 2, 3, 4, 5];println!("Using for loop:");for num in numbers {println!(" Number: {}", num);}println!("\nUsing while loop:");let mut count = 0;while count < 3 {println!(" Count is: {}", count);count += 1;}println!("\nUsing infinite loop with break:");let mut i = 0;let result = loop {i += 1;if i == 3 {break i * 2;}};println!(" Loop result: {}", result);}
Breakdown
1
for num in numbers
Iterates over each element in the array, binding it to `num`.
2
while count < 3
Executes the block repeatedly as long as the condition is true.
3
let result = loop { ... break i * 2; }
Infinite loop that breaks with a computed value that becomes the result.