Rust Basics
Rust if, else if and else
Run code only when a condition is true, and use if as an expression that returns a value.
What you'll learn
- if, else if, else
- Conditions must be bool
- if as an expression
score = 87
- 1
score >= 90false, skip - 2
score >= 70true - 3
"Good"this branch runs
The first true branch runs
An if statement runs a block only when its condition is true. The condition must be a bool: Rust does not treat numbers as true or false.
The conditions are checked from top to bottom and only the first true branch runs, so 87 prints Good. Because if is an expression, it can produce a value for let: every branch must then return the same type.
Key points
- Conditions are checked from top to bottom.
- Only the first true branch runs.
- let grade = if ... { 'A' } else { 'B' }; stores the result.
Runnable Rust example
Rust
main.rs
fn main() {
let score = 87;
if score >= 90 {
println!("Excellent");
} else if score >= 70 {
println!("Good");
} else {
println!("Keep practicing");
}
let grade = if score >= 90 { 'A' } else if score >= 80 { 'B' } else { 'C' };
println!("Grade: {grade}");
}
Good
Grade: BPractice
Open the example in the online compiler, change a value or add a line, and predict the output before you run it. Then break the code on purpose and read the compiler's message.
Finished this lesson?
Mark it as learned to track your progress.
Your progress is saved in this browser Sign in to keep it on every device.
Practice with a challenge
Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.
- Letter Grade Turn a test score into a letter grade. Easy
- Leap Year Check whether a year follows the Gregorian leap-year rule. Easy