In Rust, if is not just a statement (like in many other programming languages) — it is also an expression.
This means it can return values, making Rust’s conditional logic both powerful and flexible.
In this tutorial, we’ll cover:
- The basics of
if - Using
else ifandelse - Using
ifas an expression (returning a value) - Common mistakes to avoid
The Basics of Rust if-else Statement #
The simplest form of if checks whether a condition is true:
fn main() {
let number = 7;
if number < 10 {
println!("The number is less than 10");
}
}
Code language: Rust (rust)- The condition (
number < 10) must be a boolean value (trueorfalse). - Unlike some languages, Rust does not automatically convert numbers to booleans.
Valid:
if number < 10 { ... }
Code language: Rust (rust)Invalid (will not compile):
if number { ... } // ERROR: expected `bool`, found integer
Code language: Rust (rust)Using else if and else #
You can add multiple conditions with else if and a fallback with else:
fn main() {
let number = 15;
if number < 10 {
println!("The number is less than 10");
} else if number < 20 {
println!("The number is between 10 and 19");
} else {
println!("The number is 20 or greater");
}
}
Code language: Rust (rust)- The first condition that is true will run.
- If none are true, the
elseblock runs. - Only one branch is executed.
Using if as an Expression #
Here’s where Rust is special: if can return values.
fn main() {
let number = 3;
let result = if number % 2 == 0 {
"even"
} else {
"odd"
};
println!("The number is {}", result);
}
Code language: Rust (rust)ifandelseblocks must return the same type.- Both branches return a string slice (
&strin this example).
This code will not compile:
let result = if number % 2 == 0 {
5
} else {
"odd" // ERROR: mismatched types
};
Code language: Rust (rust)Common Mistakes to Avoid #
Forgetting braces {}
In Rust, braces are always required around the block of code after if, else if, or else.
if number < 10 println!("Too small"); // ERRORCode language: Rust (rust)Correct:
if number < 10 {
println!("Too small");
}Code language: Rust (rust)Mismatched types in expressions
Both branches of if must evaluate to the same type (or () if no value is returned).
Rust if-else Example: Grading System #
Let’s put everything together:
fn main() {
let score = 85;
let grade = if score >= 90 {
"A"
} else if score >= 80 {
"B"
} else if score >= 70 {
"C"
} else if score >= 60 {
"D"
} else {
"F"
};
println!("Your grade is {}", grade);
}
Code language: Rust (rust)Output:
Your grade is B
Summary #
ifchecks conditions and requires a boolean.- Use
else iffor multiple conditions andelseas a fallback. ifis an expression in Rust — it can return values.- Both branches of an
ifexpression must return the same type. - Always use braces
{}for clarity and safety.