Control Flow
if in Rust is an expression, not just a statement — it can produce a value, which is why you can assign the result of an if/else directly to a variable instead of declaring the variable first and assigning inside each branch.
main.rs
Try it yourself →fn main() {
let number = 7;
let description = if number % 2 == 0 {
"even"
} else {
"odd"
};
println!("{} is {}", number, description);
}Output
7 is odd
loop, while, and for
loop runs forever until you break out of it explicitly — and break can carry a value out of the loop, becoming the loop expression's result, which while and for can't do since they're not meant to compute a value. for iterates a range or collection directly, without any manual index bookkeeping.
main.rs
Try it yourself →fn main() {
let mut count = 0;
let result = loop {
count += 1;
if count == 5 {
break count * 2;
}
};
println!("result = {}", result);
for i in 0..3 {
println!("i = {}", i);
}
}Output
result = 10 i = 0 i = 1 i = 2
Next: vectors — Rust's growable array type.
Practice exercise
Set a variable score: i32 = 73. Use an if/else expression to set a variable grade to "pass" if score is 60 or above, otherwise "fail", then print grade.