What if-else adds
A plain if does something when a condition is true and nothing otherwise. Often you want a different action in the other case. In plain words: if I'm tired, I take a nap; otherwise, I start coding. Rust writes that with else.
let am_tired = false;
if am_tired {
println!("I take a nap");
} else {
println!("I start coding");
}
I start coding
Here am_tired is false, so Rust skips the first block and runs the one after else. Setting am_tired to true flips the output to I take a nap. Exactly one of the two blocks always runs.
Rules for else
- It needs an
if. Anelsecan't stand alone. It always belongs to theifjust before it. - It has no condition. It catches whatever the
ifdidn't: if the condition is false, theelseblock runs. - By convention it sits on the same line as the closing brace. Write
} else {. Puttingelseon the next line compiles, but it is not the standard Rust layout. - Its braces are required. As with
if, the block always has curly braces, and the condition of theifneeds no parentheses.
Chaining with else if
When there are more than two outcomes, add else if branches. Rust checks them in order and runs the first one whose condition is true. A final else handles the rest:
let score = 7;
if score >= 9 {
println!("excellent");
} else if score >= 5 {
println!("pass");
} else {
println!("fail");
}
pass
Order matters. With a score of 9, both of the first two conditions are true, but only the first block runs, because the chain stops at the first match.
if-else is an expression
In Rust, an if-else produces a value, so it can sit on the right side of a let. Both branches must produce the same type, and the final expression of each block has no semicolon:
let passed = true;
let message = if passed { "Passed" } else { "Failed" };
println!("{}", message);
Passed
This replaces the ternary operator found in other languages, which Rust doesn't have. Without an else, the expression form would be a compile error, because the compiler can't give message a value when the condition is false.
Nesting
A block can contain any statements, including another if. Nesting is useful when the second decision only matters after the first one:
let am_tired = false;
let has_deadline = true;
if am_tired {
println!("I take a nap");
} else {
if has_deadline {
println!("I start coding");
} else {
println!("I read a book");
}
}
I start coding
This particular case is just else if has_deadline, and the flatter version is easier to read. Reach for nesting only when the inner decision really belongs inside one branch.
The exercise
The starting code already holds an if:
let passed: bool = false;
if passed {
println!("Passed the test");
}
With passed set to false, this prints nothing. The step asks you to attach an else branch that prints "Failed the test" with println!. Put else on the same line as the } that closes the if block, then close the new block with its own }:
let passed: bool = false;
if passed {
println!("Passed the test");
} else {
println!("Failed the test");
}
Now the program always reports a result. With false it prints Failed the test.
Choosing between if and if-else
Use a plain if when there is nothing to do in the false case, such as printing a warning only when something is wrong. Use if-else when both outcomes need a response, such as reporting a pass or a failure. If you find yourself writing two if statements with opposite conditions, one if-else says the same thing more clearly.
Common mistakes
- Writing a condition after
else.else passed { ... }is a syntax error. For a second condition useelse if. - Leaving out the braces. Both blocks need them, even with one statement inside.
- Adding a semicolon after the closing brace of the
if.};beforeelseends the statement early and theelsethen has noif. - Branches of different types in an expression.
let x = if c { 1 } else { "no" };doesn't compile. - Two separate
ifstatements instead ofif-else. Separate ones can both run, or both be skipped, whileif-elseguarantees exactly one block.
Key takeaways
elseruns when theifcondition is false, and it never has a condition of its own.- Write
} else {on one line. - Use
else iffor more than two outcomes. The first true branch wins. - An
if-elsecan produce a value, which is how Rust does what a ternary operator does elsewhere.
