match expression for pattern matching.
It is a powerful construct that applies both to types and expressions.
match for union types
Pattern matching for unions is a key to message handling.
match for a union must be exhaustive
In other words, all alternatives must be covered.
else is not allowed for unions but is permitted for a lazy match.
Syntax details
- After
=>there is- either a block:
A => { ... } - or an expression:
A => 123 - or
A => return SOME_EXPR - or
A => throw ERR_CODE
- either a block:
- A comma
- optional after a block:
A => {} B => {} - required otherwise:
A => 1, B => 2
- optional after a block:
- May be used as a match expression:
return match (v) { ... } - Variable declarations are allowed inside:
match (val v = ...)
Using match as an expression
Using match in expression position allows:
var smth = match (v) { ... }return match (v) { ... }- and similar
Declaring variables inside match
match for expressions (not for types)
match can be used with constant expressions, similar to switch:
- only constant expressions may appear before
=> elseis required for match expressions and optional for statements
All comparable types supported — for instance, addresses and enums.
match for enums
Pattern matching on enums requires coverage of all cases (exhaustive):
else to handle remaining values:
Familiar with Rust's enum and match?Note that
match is similar in spirit, but enum values in Tolk are backed by integers; union types are more general and expressive.