rust / beginner
Snippet
Rust Loop Constructs: loop, while, and for
Rust provides three main loop constructs. 'loop' creates an infinite loop that can break with a value. 'while' loops execute as long as a condition is true. 'for' loops iterate over ranges or iterators and are the most idiomatic way to loop in Rust, providing both safety and readability.
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
27
28
29
fn main() {// Infinite loop with breaklet mut count = 0;let result = loop {count += 1;if count == 3 { break count * 2; }};println!("Loop result: {}", result);// While looplet mut n = 0;while n < 3 {print!("{} ", n);n += 1;}println!();// For loop with rangefor i in 0..3 {print!("{} ", i);}println!();// For loop with iteratorlet items = vec![10, 20, 30];for item in items.iter() {print!("{} ", item);}}
Breakdown
1
loop { ... break count * 2; }
Infinite loop that returns a value via break
2
while n < 3 { ... }
Condition-based loop that checks before each iteration
3
for i in 0..3 { ... }
Range iteration from 0 (inclusive) to 3 (exclusive)
4
for item in items.iter() { ... }
Iterates over a collection using an iterator