Conditions
If expression
if
expressions are pretty straightforward and similar to most other languages.
Unlike other C-like languages,
there are no parentheses surrounding the condition and the braces are always required.
if
can be used as an expression, last expression is the value of a block:
If you're using if as an expression, for example, for returning its value or assigning it to a variable, the else branch is mandatory.
Therefore, there is no ternary operator (condition ? then : else
) because ordinary if
works fine
in this role.
If unwrapping
To handle Result/Optional types, there is a special if
:
See Error handling for more information.
Match expression
A match
statement is a shorter way to write a sequence of if-else
statements.
When a matching branch is found, the following statement block will be run.
The else
branch will be run when no other branches match.
A match
statement can also to be used as an if-else if-else
alternative:
or as an unless
alternative:
A match
expression returns the value of the final expression from the matching branch.
A match
statement can also be used to branch on the variants of an enum
by using the shorthand .variant_here
syntax.
An else
branch is not allowed when all the branches are exhaustive.
You can also use ranges as match
patterns.
If the value falls within the range of a branch, that branch will be executed.
Note that the ranges use ...
(three dots) rather than ..
(two dots).
This is because the range is inclusive of the last element, rather than exclusive
(as ..
ranges are).
Using ..
in a match
branch will throw an error.
Constants can also be used in the range branch expressions.
match
as an expression is not usable infor
loop andif
statements.