Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

The match statement allows to evaluate an expression and run actions depending on the obtained value. The value may tested using:

Example:

Other value.
Between 0 and 5 excluded.
Other value.
Some number in 7, 13, 20.
Exactly 10!
()

The actions may themselves be expressions, in which case they must all return the same type. Example:

(-50, 10)
(3, 1)
(46, 10)
(7, 2)
(10, 3)
()

13.3.1Missing cases

match must be exhaustive and cover all cases, otherwise the compiler will raise an error:

[E0004] Error: non-exhaustive patterns: `i32::MIN..=-101_i32` and `100_i32..=i32::MAX` not covered
   ╭─[ command_4:1:1 ]
   │
 2 │ match n {
   │       ┬  
   │       ╰── patterns `i32::MIN..=-101_i32` and `100_i32..=i32::MAX` not covered
 3 │   -100..100 => println!("My single case.")
   │                                           │ 
   │                                           ╰─ help: ensure that all possible cases are being handled by adding a match arm with a wildcard pattern, a match arm with multiple or-patterns as shown, or multiple match arms: `,
  i32::MIN..=-101_i32 | 100_i32..=i32::MAX => todo!()`
───╯

13.3.2Using variables

For each match case, we may set the matched value into a variable that we can use:

For instance, if we define the following function:

We may test its returned values with match, and set them into a variable n:

-100 is <= -10.
Between 0 and 7 excluded: 6.
Other value: 92.
Exactly 10!
Other value: 14.
20 is in 7, 13, 20.
()

13.3.3Handling floats

Float values can be used inside a match statement. One way to match them is to use float ranges:

Second case
()

Another way is to use variables with if statements:

Fourth case: 3.7
()
[(0.3, 3.4), (1.2, 2.7), (2.0, 2.9), (4.0, 3.2)]

see solution

13.3.4With variants

The match statement is often used on enum values or variants. Match cases can extract data stored inside the variants.

Here is an enum type Color that defines two variants. One for grey levels, and another for RGB colors:

The following match statement extracts variants’ data in both cases:

Grey level 99.
RGB color (10, 30, 60).
()

see solution