Conditions and loops
if as an expression, match, and the three loops: for over a range or iterator, while, and loop with break value.
Runs in Zerethon IDE · Rust 1.87
Official Rust documentation ↗
main.rs
fn main() {
for n in 1..=5 {
if n % 2 == 0 {
println!("{n} even");
} else if n == 5 {
println!("{n} last");
} else {
println!("{n} odd");
}
}
let mut i = 3;
while i > 0 {
i -= 1;
if i == 1 {
continue;
}
println!("i = {i}");
}
for (index, fruit) in ["apple", "pear"].iter().enumerate() {
println!("{index} {fruit}");
}
let day = 6;
let kind = match day {
0 | 6 => "weekend",
1..=5 => "weekday",
_ => "unknown",
};
println!("{kind}");
let mut n = 0;
let found = loop {
n += 7;
if n % 5 == 0 {
break n;
}
};
println!("{found}");
}
Output
1 odd 2 even 3 odd 4 even 5 last i = 2 i = 0 0 apple 1 pear weekend 35
1..5stops before 5;1..=5includes it.- The condition of
ifmust be abool—if n { }with a number does not compile. matchmust cover every possible value;_matches anything that is left.ifandmatchare expressions:let kind = if x > 0 { "pos" } else { "neg" };.