So far every program has run every line, top to bottom. A study planner needs to react to its data: if today's minutes reached the goal, say so; otherwise, encourage another session. An if lets a program choose which block of code to run.
The choice is based on a condition, an expression that is either true or false. Values like these have the type bool, short for boolean. Comparisons produce them:
a == bis true when the values are equal (two equals signs; one=is assignment).a != bis true when they differ.a < banda > bcompare strictly.a <= banda >= balso accept equality.
An if runs its first block when the condition is true. An else block runs when it is false. Rust needs braces around both blocks, even for a single line, but no parentheses around the condition.
Predict and run
Be precise at boundaries. A goal of 30 minutes includes exactly 30 if you use >=, and excludes it if you use >. Which line runs when the value is exactly the goal?
fn main() {
let minutes = 30;
let goal = 30;
if minutes >= goal {
println!("Goal reached");
} else {
println!("Keep going");
}
}Check your prediction
Goal reached30 >= 30 is true, so the first block ran and the else block was skipped. Exactly one of the two blocks always runs. Change >= to > and predict again: now 30 > 30 is false and you get Keep going. To tell the two operators apart, a test must include the boundary value itself; 29 and 31 behave the same with either one.
Conditions must be booleans
Some languages treat any non-zero number as true. Rust does not guess:
fn main() {
let minutes = 30;
if minutes {
println!("Studied today");
}
}This fails with error[E0308]: mismatched types, pointing at minutes with expected bool, found integer. Say what you mean with a comparison, such as if minutes > 0. An if without an else is fine: when the condition is false, nothing happens.
if produces a value
In Rust, an if is an expression: it can produce a value, just as 2 + 3 does. Put the value as the last line of each block, without a semicolon, and bind the whole if to a name.
fn main() {
let minutes = 45;
let goal = 30;
let label = if minutes >= goal { "Goal reached" } else { "Keep going" };
println!("{minutes} min: {label}");
let extra = if minutes > goal { minutes - goal } else { 0 };
println!("Extra minutes: {extra}");
}45 min: Goal reached
Extra minutes: 15Because label must have one type, both branches must produce the same type. Mixing text and a number fails with error[E0308]: if and else have incompatible types. An if used as a value also needs an else, since the binding needs a value either way.
More than two paths
Chain conditions with else if. Rust checks them from top to bottom and runs the first block whose condition is true, then skips the rest. Order matters: put the most demanding test first.
fn main() {
let minutes = 20;
if minutes >= 45 {
println!("Long session");
} else if minutes >= 15 {
println!("Short session");
} else {
println!("Too short to count");
}
}Short session20 fails the first test and passes the second, so the third block never runs. If you swapped the first two tests, a 50-minute session would also pass minutes >= 15 first and be called short. You can also combine tests: && means "and", || means "or". For example, minutes >= 15 && minutes < 45 describes the short range on its own.
Test the edges
For every boundary in a condition, try the value just below it, the value itself and the value just above it. Most mistakes in conditions hide at exactly one of those three.
Practice
Your turn
Given minutes = 15, print Short session for values below 20, Full session for 20 to 45 and Long session for anything above 45. Then test 19, 20, 45 and 46 and predict each result before you run.
fn main() {
let minutes = 15;
println!("{minutes}");
}Hint 1: the idea
There are three groups, so you need if, else if and else. Decide where 20 and 45 belong before you write the comparisons.
Hint 2: a first step
Start with if minutes < 20. In the else if, ask whether the value is still at most 45 with <=.
Worked solution
fn main() {
let minutes = 15;
if minutes < 20 {
println!("Short session");
} else if minutes <= 45 {
println!("Full session");
} else {
println!("Long session");
}
}Short sessionThe else if only runs when minutes < 20 was false, so it does not need to check minutes >= 20 again. 20 and 45 both print Full session, while 19 and 46 land in the groups on either side, which is exactly what the four test values confirm. In the next lesson you apply a decision like this to every session in a list.
Completion is saved in this browser only. It does not measure mastery.