If and else
Quick answer
if chooses a block based on a boolean condition. An optional else block runs when that condition is false. Use else if for a series of alternatives, checked in order. An if expression can also produce a value.
Conditions and branch results
A condition must have type bool. Rust does not require parentheses around the condition, but branch bodies use braces. When an if expression supplies a value, its branches must have compatible types; for a meaningful two-way value, supply an else branch as well.
fn main() { let score = 72; if score >= 80 { println!("Excellent"); } else if score >= 60 { println!("Passed"); } else { println!("Try again"); }}Expected stdout (not executed):
PassedThe first condition is false and the second is true, so only the second block runs.
fn main() { let members = 3; let fee = if members >= 3 { 5 } else { 8 }; println!("Fee: {fee}");}Expected stdout (not executed):
Fee: 5Both branches yield integers, so fee receives the selected integer.
Common mistake
Putting the broader condition first may hide a narrower else-if case. Check the most restrictive threshold first when the categories overlap.
Try it yourself
Classify a temperature as cold below 10, mild below 25, or warm otherwise. Test the two boundary values.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
If and else — practice quiz
Choose one answer per question, then review the explanation.
A score of 85 meets both `score >= 80` and `score >= 60` in an if / else if chain. Which branch runs?
Which expression assigns an integer to fee using two branches?
What does `if false { println!("A"); }` do in main?