Try Install Learn Blog API Packages GitHub
Pages

case

A case expression looks like this:

case (condition) {
  match1 => value1
  match2 => value2
  match3 => value3
  => defaultValue
}

It returns the value of the first branch that matches the condition, or the default if none matched.

There are some rules that will be enforced by either the parser or the compiler:

  • the condition can be any type
  • the matches of branches must be the same type as the condition
  • the values of the branches must be the same type

case expressions are compiled to JavaScript if...else statements under the hood.

Matching an Enum

Enums can be matched using a case expression to destructure its variants values like so:

case (result) {
  Result::Err error => /* do something with the error */
  Result::Ok value => /* do something with the value */
}

Matching a Tuple

Tuples can be matched using a case expression like so:

case ({"First", 0, true}) {
  {first, second, third} => /* do something with the variables */
}

Matching an Array

Arrays can be matched using a case expression like so:

case (["first", "second", "third"]) {
  [first, second, third] => /* do something if it only has three elements */
  [head, ...tail] => /* do something otherwise with the head and tail */
}