Rust If...Else
if lets your program make decisions — run one block of code or another, depending on a condition.
Basic if
Section titled “Basic if”fn main() { let age = 20;
if age >= 18 { println!("You can vote"); }}A couple of things to notice, since they trip people up coming from other languages:
- No parentheses around the condition —
if age >= 18, notif (age >= 18). - The condition must be a real
bool.if age(a number) won’t compile — you needif age != 0or similar.
if / else
Section titled “if / else”fn main() { let age = 15;
if age >= 18 { println!("You can vote"); } else { println!("Not old enough yet"); }}else if for more branches
Section titled “else if for more branches”fn main() { let score = 72;
if score >= 90 { println!("Grade: A"); } else if score >= 75 { println!("Grade: B"); } else if score >= 60 { println!("Grade: C"); } else { println!("Grade: F"); }}Rust checks each condition top to bottom and runs the first one that matches, just like you’d expect.
Using if as an expression
Section titled “Using if as an expression”Here’s something Rust does that a lot of languages don’t: if can produce a value. That means you can use it on the right side of a let:
fn main() { let age = 20; let status = if age >= 18 { "adult" } else { "minor" };
println!("{status}");}This works the same way returning a value from a function does — no semicolon after the value in each branch. The one requirement: both branches must produce the same type (here, both are &str).
if condition { ... }— no parentheses needed; the condition must be abool.- Chain more checks with
else if, and fall back withelse. ifcan be used as an expression to produce a value — both branches must match in type, and you need anelse.
Quick check
Section titled “Quick check”Quick check
1. Which of these is required for a Rust if condition?
2. When using if as an expression with let, what's required of both branches?
Score: 0 / 2