Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Match Expression

A match expression dispatches on a value of enumeration type: the value selects an arm, and the selected arm's function is applied on the variant's payload to produce a result.

Process

At runtime:

  1. the scrutinee expression is evaluated;
  2. the variant denoted by its value selects the arm whose pattern references that variant; and
  3. the selected arm's function is called with the variant's payload as its argument, and its result is the match's value.

Assertions

  1. The scrutinee is a value of an enumeration type.
  2. Each arm's pattern references a distinct variant of that enumeration type.
  3. Every variant of that enumeration type is referenced by exactly one arm.
  4. Each arm's body is a value of a function type whose parameters match the referenced variant's payload: a payload-less variant requires a function with no parameters; otherwise, a single parameter of the variant's payload type is required.
  5. The arms' functions' return types have a common type, the selected arm's return value is implicitly converted to that type, and the match expression has that type.

Syntax

match_pattern = symbol_reference, { static_access_operation } ;

match_arm = match_pattern, colon, expression, semicolon ;

match_expression = match, left_paren, expression, right_paren, left_brace, { match_arm }, right_brace ;