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. A test against a pattern binds the names the pattern declares, in scope in the branch the test guards and in the operands after it in a chain of &&:
if entry is .Some(value) {
Use(value);
}
if error is .NotADigit(c) && c != ' ' {
Report(c);
}
The names are not in scope in an else branch or after the statement, and a test that binds names under || or ! is an error.
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 as a value
The same if is also a value wherever an expression is expected: each branch is a block that yields the expression it ends with when that expression has no ;, and the else is required. It takes the place of the conditional operator c ? a : b, which Rux does not have — see Conditional values:
let label = if count == 1 { "item" } else { "items" };
let size = match count {
0 => "none",
1 => "one",
_ => "many"
};
An if at the start of a statement is the statement, and its value is not used: a branch may end with an expression that yields (), such as a call that returns nothing, without its ;, but a branch that ends with any other value is error: this branch yields a value of type 'int' that is not used, with help: add ';' or use the value. An if that ends a value block and yields a value is that block's value.
A var declared without a value and assigned in each branch works too; 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 values —
ifas a value, and value blocks - match — choosing by the shape of a value
- Learn: If, Else if