Conditionals
Rust's if works like every other language's at first glance, but with one real difference: if is an expression, not a statement, so it can produce a value directly — which is also why Rust has no separate ternary operator.
if / else if / else
fn main() { let temp = 15; if temp > 30 { println!("Hot"); } else if temp > 15 { println!("Mild"); } else { println!("Cold"); } }
Cold
No parentheses are needed around the condition (unlike C or Java), but the curly braces are never optional — there's no single-statement-without-braces shorthand.
if as an expression
Because if produces a value, you can assign its result directly to a variable instead of declaring the variable first and reassigning it in each branch:
fn main() { let age = 20; let category = if age >= 18 { "adult" } else { "minor" }; println!("{}", category); }
adult
Both branches produce values of the same type here (&str) — that's not a style choice, it's required. An if used as an expression must have every branch evaluate to the exact same type, and it must have an else, since the compiler needs to know what value comes out no matter which branch runs.
let category = if age >= 18 { "adult" } else { 0 };
error[E0308]: `if` and `else` have incompatible types | | let category = if age >= 18 adult else 0; | ------- ^ expected `&str`, found integer | | | expected because of this
? : ternary operator — if as an expression already covers that use case, and reads more clearly once you're used to it. For matching against several specific values rather than a single condition, the match expression (covered in the Enums & Pattern Matching lesson) is usually the better tool.