Beginner Fundamentals
Conditionals
Conditionals run different code depending on a boolean condition. In Rust, if/else works as a statement and also as an expression that produces a value.
Basic if/else
The condition must be a bool; Rust does not treat numbers as truthy.
fn main() {
let number = 7;
if number > 5 {
println!("Greater than five");
} else {
println!("Five or less");
}
}
else if
fn main() {
let score = 75;
if score >= 90 {
println!("A");
} else if score >= 70 {
println!("B");
} else {
println!("C");
}
}
if as an expression
Because if returns a value, you can assign its result directly. Both branches must produce the same type.
fn main() {
let age = 20;
let category = if age >= 18 { "adult" } else { "minor" };
println!("{}", category);
}
This replaces the ternary operator found in other languages and keeps the code expressive and concise.