published: 16th of February 2022
A for expression extracts values from an iterator until the iterator is empty. for loops in Rust use a similar syntax to Python with the in keyword.
// Example for loop.
for i in vec!["stuff", "things"] {
print!("{} ", i);
} // => stuff things
// Mark a loop level with a tag: {'outer} to use as a break reference point.
'outer: for i in vec!["stuff", "things", "blah"] {
for j in vec!["bleh", "blah", "blow"] {
if i == j {
println!("i: {} j: {}", i, j);
break 'outer; // Breaks out of the loop at the {'outer} tag.
}
}
} // => i: blah j: blah
A while expression executes the loop body as long as some conditional expression evaluates to true.
// Example while loop.
let mut tick = 3;
while tick >= 0 { // conditional expression => `tick >= 0`
if tick == 0 {
print!("BOOM!");
} else {
print!("{} ", tick);
}
tick -= 1;
} // => 3 2 1 BOOM!
A loop expression executes an unconditional infinite loop.
// Example unconditional loop.
loop {
println!("💵 make it rain 💵");
} // => All the moneys
https://www.manning.com/books/rust-in-action
https://www.udemy.com/course/ultimate-rust-crash-course/
https://doc.rust-lang.org/std/keyword.for.html
https://doc.rust-lang.org/std/keyword.while.html
https://doc.rust-lang.org/std/keyword.loop.html
https://doc.rust-lang.org/reference/expressions/loop-expr.html#predicate-loops