Conditionals
Prerequisites: Reading user input
Syntax
if condition {
// runs when condition is true
} else if other_condition {
// runs when the first is false and this one is true
} else {
// runs otherwise
}
- No parentheses are needed around the condition, but the braces are always required, even for a single line.
- The condition must be a
bool. Rust has no "truthiness": a number, string, or empty collection is never treated as true or false automatically. Write the comparison you mean, such ascount != 0or!name.is_empty().
if is an expression, meaning it produces a value. You can use it
on the right-hand side of let, much like the ternary a ? b : c
operator in other languages (Rust doesn't have ?:):
let label = if n % 2 == 0 { "even" } else { "odd" };
When if is used this way, every branch must produce the same
type, and an else is required.
Example
fn main() {
let temperature = 23;
if temperature > 30 {
println!("Hot");
} else if temperature > 15 {
println!("Pleasant");
} else {
println!("Cold");
}
let n = 7;
let kind = if n % 2 == 0 { "even" } else { "odd" };
println!("{n} is {kind}");
let cart_items = 0;
if cart_items != 0 {
println!("Ready to check out");
} else {
println!("Your cart is empty");
}
let age = 20;
let has_id = true;
if age >= 18 && has_id {
println!("Entry allowed");
}
}
Expected output
Pleasant
7 is odd
Your cart is empty
Entry allowed
Common mistakes
- Using a number as a condition.
if items { ... }whereitemsis an integer fails:
error[E0308]: mismatched types
The label under it reads "expected bool, found integer". Write
if items != 0 instead.
- Branches of different types.
let value = if ok { 5 } else { "five" };fails with:
error[E0308]: `if` and `else` have incompatible types
- Putting a semicolon after the values in an
ifexpression ({ "even"; }). That turns the value into a statement, and the branch produces()instead.
Practice
Store a score of 85 in a variable. Use an if expression to set a
grade variable to "A" for 90 or more, "B" for 80 or more, "C"
for 70 or more, and "F" otherwise, then print Score 85: grade B.
Show solution
fn main() {
let score = 85;
let grade = if score >= 90 {
"A"
} else if score >= 80 {
"B"
} else if score >= 70 {
"C"
} else {
"F"
};
println!("Score {score}: grade {grade}");
}