Skip to content

Rust If...Else

if lets your program make decisions — run one block of code or another, depending on a condition.

fn main() {
let age = 20;
if age >= 18 {
println!("You can vote");
}
}
▶ Try it Yourself

A couple of things to notice, since they trip people up coming from other languages:

  • No parentheses around the condition — if age >= 18, not if (age >= 18).
  • The condition must be a real bool. if age (a number) won’t compile — you need if age != 0 or similar.
fn main() {
let age = 15;
if age >= 18 {
println!("You can vote");
} else {
println!("Not old enough yet");
}
}
▶ Try it Yourself
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");
}
}
▶ Try it Yourself

Rust checks each condition top to bottom and runs the first one that matches, just like you’d expect.

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}");
}
▶ Try it Yourself

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 a bool.
  • Chain more checks with else if, and fall back with else.
  • if can be used as an expression to produce a value — both branches must match in type, and you need an else.