If, Loops & Match in Rust
From the Rust cheat sheet ยท Control Flow ยท verified Jul 2026
If, Loops & Match
Conditional expressions, loops, and pattern matching.
rust
// If expression (returns a value)
let status = if age >= 18 { "adult" } else { "minor" };
// Loops
for item in &items { println!("{item}"); }
for i in 0..5 { println!("{i}"); } // 0,1,2,3,4
while count > 0 { count -= 1; }
let result = loop { break 42; }; // loop returns a value
// Match
match value {
1 => println!("one"),
2 | 3 => println!("two or three"),
4..=9 => println!("four to nine"),
_ => println!("other"),
}๐ก if and match are expressions โ they return values, so you can assign them to variables
โก if let is sugar for matching a single pattern โ cleaner than a full match for Option/Result
๐ let-else (let Some(x) = val else { return }) is the idiomatic "unwrap or bail" pattern
๐ข Match is exhaustive โ the compiler forces you to handle every possible case
ifloopsmatchpattern-matching