if
expressions
Syntax
IfExpression →
if Conditions BlockExpression
( else ( BlockExpression | IfExpression ) )?
Conditions →
Expressionexcept StructExpression
| LetChain
LetChain → LetChainCondition ( && LetChainCondition )*
LetChainCondition →
Expressionexcept ExcludedConditions
| OuterAttribute* let Pattern = Scrutineeexcept ExcludedConditions
ExcludedConditions →
StructExpression
| LazyBooleanExpression
| RangeExpr
| RangeFromExpr
| RangeInclusiveExpr
| AssignmentExpression
| CompoundAssignmentExpression
The syntax of an if
expression is a sequence of one or more condition operands separated by &&
,
followed by a consequent block, any number of else if
conditions and blocks, and an optional trailing else
block.
Condition operands must be either an Expression with a boolean type or a conditional let
match.
If all of the condition operands evaluate to true
and all of the let
patterns successfully match their scrutinees,
the consequent block is executed and any subsequent else if
or else
block is skipped.
If any condition operand evaluates to false
or any let
pattern does not match its scrutinee,
the consequent block is skipped and any subsequent else if
condition is evaluated.
If all if
and else if
conditions evaluate to false
then any else
block is executed.
An if
expression evaluates to the same value as the executed block, or ()
if no block is evaluated.
An if
expression must have the same type in all situations.
if let
patterns
let
patterns in an if
condition allow binding new variables into scope when the pattern matches successfully.
The following examples illustrate bindings using let
patterns:
Multiple patterns may be specified with the |
operator.
This has the same semantics as with |
in match
expressions:
Chains of conditions
Multiple condition operands can be separated with &&
.
Similar to a &&
LazyBooleanExpression, each operand is evaluated from left-to-right until an operand evaluates as false
or a let
match fails,
in which case the subsequent operands are not evaluated.
The bindings of each pattern are put into scope to be available for the next condition operand and the consequent block.
The following is an example of chaining multiple expressions, mixing let
bindings and boolean expressions, and with expressions able to reference pattern bindings from previous expressions:
The above is equivalent to the following without using chains of conditions:
If any condition operand is a let
pattern, then none of the condition operands can be a ||
lazy boolean operator expression due to ambiguity and precedence with the let
scrutinee.
If a ||
expression is needed, then parentheses can be used. For example:
2024 Edition differences
Before the 2024 edition, let chains are not supported. That is, the LetChain grammar is not allowed in an
if
expression.