Sub topic 2
Repeating with `loop` and `while`
This chapter assumes basic Rust syntax, primitive types, variables, mutability, and running programs with Cargo. Rust loops are expressions or statements that control repeated execution.
`loop` and `while`
A loop repeats forever until break exits it. A while repeats while its condition is true.
fn main() {
let mut count = 0;
loop {
count += 1;
println!("{count}");
if count == 3 {
break;
}
}
let mut fuel = 2;
while fuel > 0 {
println!("fuel: {fuel}");
fuel -= 1;
}
}Use loop when the stopping decision happens inside the body. Use while when the condition clearly describes whether another iteration should begin.
Iterating with `for` and ranges
A for loop visits each item in an iterator. A range creates a sequence of integers. The .. range excludes its upper bound; ..= includes it.
fn main() {
for n in 1..=3 {
println!("{n}");
}
for n in (1..=3).rev() {
println!("countdown: {n}");
}
for word in ["safe", "fast", "clear"] {
println!("{word}");
}
}for is usually clearer than manually controlling an index or counter.
Labels and values from loops
A loop can return a value through break value. A label, such as 'search, identifies a loop so an inner loop can stop the outer one.
fn main() {
let mut n = 0;
let first_big = loop {
n += 1;
if n * n > 20 {
break n;
}
};
println!("first value: {first_big}");
'search: for x in 1..=5 {
for y in 1..=5 {
if x * y == 12 {
println!("{x} × {y}");
break 'search;
}
}
}
}Branching with `match`
match compares a value against patterns. Every possible value must be covered, often with _ as a final fallback.
fn describe(n: i32) -> &'static str {
match n {
i32::MIN..=-1 => "negative",
0 => "zero",
n if n % 2 == 0 => "positive even",
_ => "positive odd",
}
}
fn main() {
println!("{}", describe(7));
}A match arm can include a range, bind a value, or add a guard with if.
Exercise
Which construct best fits visiting every number from 1 through 5, and why?
Show answer
Use for n in 1..=5, because for iterates over the inclusive range without manual counter management.