BeginnerLesson 3 of 16
Conditions & Loops – Rust
if as an expression, loop, while, for, and ranges.
if needs no parentheses around the condition, but it does need curly braces around the block. The condition must be a bool (no “truthy” values). Because if is an expression, it produces a value:
fn main() {
let punkte = 73;
let note = if punkte >= 90 {
"very good"
} else if punkte >= 70 {
"good"
} else {
"needs improvement"
};
println!("{note}"); // good
}Rust has three loops: loop (infinite, can produce a value via break value), while, and for. You write ranges as 0..3 (end excluded) or 1..=3 (end included).
fn main() {
for i in 0..3 {
println!("Round {i}"); // 0 1 2
}
for i in (1..=3).rev() {
println!("{i}"); // 3 2 1
}
let mut n = 0;
while n < 3 {
n += 1;
}
let ergebnis = loop {
n += 1;
if n == 10 {
break n * 2;
}
};
println!("{ergebnis}"); // 20
}You iterate over collections directly with for. Labels let you break out of nested loops precisely:
fn main() {
let fruechte = ["Apple", "Pear", "Cherry"];
for (i, f) in fruechte.iter().enumerate() {
println!("{}: {}", i + 1, f);
}
'aussen: for i in 0..5 {
for j in 0..5 {
if i * j == 6 {
println!("{i}*{j}"); // 2*3
break 'aussen;
}
}
}
}TipPrefer
for over iterators instead of index-based loops: it is safer (no off-by-one errors) and the compiler translates it to equally fast code.Warning
if zahl { ... } with an integer does not compile. Write if zahl != 0.