Choose a path on purpose.
Use expressions and short-circuit evaluation to encode decisions.
01 Understand the contract
An if condition must be a bool; numbers do not convert to truthiness automatically. An if/else can produce a value, provided both branches have compatible types. Logical && and || short-circuit, so the second operand is evaluated only when needed. This lets a guard protect an operation such as division. State conditions in terms of your domain rather than clever punctuation, and test the boundary where the decision changes.
02 Make it concrete
This is a complete standard-library example. Use Rust stable with the 2024 edition. Run it locally using the Rust workbench.
fn main() {
let age = 19;
let status = if age >= 18 { "adult" } else { "minor" };
let denominator = 0;
let safe = denominator != 0 && 10 / denominator > 1;
println!("{status}, safe={safe}");
}adult, safe=false
- 1
The two status branches both return string slices.
- 2
The false first operand prevents division by zero.
- 3
Test age 17 and 18 to exercise the boundary.
cargo run -p lesson_conditions03 Mind the boundary
04 Your next build
Classify temperatures below 0 as freezing, from 0 to 29 as mild, and 30 or above as hot.
Reveal one possible solution +
fn weather(t: i32) -> &'static str {
if t < 0 {
"freezing"
} else if t < 30 {
"mild"
} else {
"hot"
}
}
fn main() {
assert_eq!(weather(-1), "freezing");
assert_eq!(weather(0), "mild");
assert_eq!(weather(30), "hot");
}05 Check your reasoning
Does if 1 compile as a condition?
Understand it.
Then make it yours.
Run the example, try your own input, and explain the boundary. Log the lesson when the idea makes sense.