if
if runs a block when a condition is true. else if tests further conditions in turn, and a final else runs when none of them held. The first branch whose condition is true runs, and the rest are skipped.
if-statement = "if" condition block
{ "else" "if" condition block }
[ "else" block ]
if x > 0 {
PrintLine("positive");
} else if x < 0 {
PrintLine("negative");
} else {
PrintLine("zero");
}
The condition
The condition is a bool, written without parentheses, and a structure literal inside it is wrapped in parentheses — the rules every condition follows, set out in Statements. Combine tests with the logical operators:
if age >= 18 && hasTicket {
Admit();
}
A type test is a bool too, so if shape is Circle { … } reads naturally.
Bodies
Every branch is a block, even for a single statement, and the braces are what end the condition. A binding declared in a branch lasts until that branch's closing brace.
if is not an expression
if chooses between statements; it does not produce a value, so let s = if ready { 1 } else { 2 }; does not parse. To choose a value, use the conditional operator or a match expression:
let label = count == 1 ? "item" : "items";
let size = match count {
0 => "none",
1 => "one",
else => "many"
};
Or declare a var and assign it in each branch; the compiler checks that every branch does — see Initialization.
if and when
when has the same shape as if but is decided by the compiler, which keeps only the branch it selects — see Conditional compilation. A chain keeps the keyword it starts with:
error: expected 'if' after 'else' in a run-time 'if' chain; 'when' is the compile-time conditional
See also
- Statements — the rules every condition follows
- Conditional — choosing between two values
- match — choosing by the shape of a value
- Learn: If, Else if