Rust If..Else
Programs need to make decisions: show a discount only to members, warn when the battery is low, pick a grade from a score. In Rust, the basic decision-making tool is if, together with its partners else if and else.
The if statement
if runs a block of code only when its condition is true:
fn main() {
let battery = 15;
if battery < 20 {
println!("Warning: battery low ({}%)", battery);
}
println!("Check complete.");
}Warning: battery low (15%)
Check complete.
Two things are different from languages like C or Java:
- No parentheses are needed around the condition. You can write
if (battery < 20), but the compiler will warn that they are unnecessary. - The curly braces are always required, even for a single line.
And as you learned in the Booleans chapter, the condition must be a real bool — if battery { ... } does not compile.
else
else provides a block that runs when the condition is false:
fn main() {
let items_in_cart = 0;
if items_in_cart > 0 {
println!("Proceed to checkout");
} else {
println!("Your cart is empty");
}
}Your cart is empty
else if
To test several conditions in a row, chain them with else if. Rust checks the conditions from top to bottom and runs only the first block whose condition is true; the rest are skipped.
fn main() {
let score = 82;
if score >= 90 {
println!("Grade: A");
} else if score >= 80 {
println!("Grade: B");
} else if score >= 70 {
println!("Grade: C");
} else {
println!("Grade: F");
}
}Grade: B
Even though 82 >= 70 is also true, only Grade: B is printed, because the first matching branch wins. The order of your conditions matters.
Tip: When you have a long chain of
else ifbranches that all compare the same value, amatchexpression (next chapter) is often clearer.
if is an expression
In Rust, if does not just run code — it produces a value. This means you can put an if on the right side of let. The value of each branch is its last expression, written without a semicolon:
fn main() {
let hour = 14;
let greeting = if hour < 12 {
"Good morning"
} else if hour < 18 {
"Good afternoon"
} else {
"Good evening"
};
println!("{}!", greeting);
let temperature = -3;
let state = if temperature <= 0 { "ice" } else { "water" };
println!("At {} degrees, it is {}.", temperature, state);
}Good afternoon!
At -3 degrees, it is ice.
This replaces the "ternary operator" (cond ? a : b) found in other languages — Rust simply does not need one.
When if is used as a value, there are two rules:
- There must be an
elsebranch, because the variable needs a value in every case. - All branches must produce the same type.
This does not compile, because one branch is a number and the other is a string:
fn main() {
let ok = true;
let value = if ok { 10 } else { "ten" };
}error[E0308]: `if` and `else` have incompatible types
--> src/main.rs:3:37
|
3 | let value = if ok { 10 } else { "ten" };
| -- ^^^^^ expected integer, found `&str`
| |
| expected because of thisNested conditions
You can place an if inside another if. Combining conditions with && and || often keeps the code flatter and easier to read, so compare both styles:
fn main() {
let age = 25;
let has_license = true;
// Nested version
if age >= 18 {
if has_license {
println!("You may rent a car.");
} else {
println!("You need a driving license.");
}
} else {
println!("You are too young to rent a car.");
}
// Flat version with a combined condition
if age >= 18 && has_license {
println!("Rental approved.");
}
}You may rent a car.
Rental approved.
Summary
| Form | Use it when |
|---|---|
if cond { } |
Something should happen only sometimes |
if cond { } else { } |
You need exactly one of two actions |
if … else if … else |
You have several mutually exclusive cases |
let x = if cond { a } else { b }; |
You want to choose a value |
Test yourself
Which of these is a valid Rust if?
- if x > 5 println!("big");
- if x > 5 { println!("big"); }
- if (x > 5) then { println!("big"); }
- if x > 5: println!("big")
What does let n = if 3 > 5 { 1 } else { 2 }; store in n?
- 1
- 2
- 3
- Compile error
With score = 95, which branch runs in if score >= 50 {A} else if score >= 90 {B} else {C}?
- A
- B
- C
- A and B