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.

Things on this page are fragmentary and immature notes/thoughts of the author. Please read with your own judgement!

:timing
:sccache 1

Tips and Traps

  1. match does a pattern matching which means each branch must be a pattern instead of an expression. Please refer to Patterns Are Not Expressions for differences between patterns and expressions.

  2. Avoid using the identifier pattern and _ in a pattern match especially when you work with a Enum. Keep in mind that explicit is better than implicit.

The following match statement won’t compile because 0 + 1 is NOT a pattern.

let x = 1;
match x {
    0 + 1 => "how",
    _ => "are",
}
    0 + 1 => "how",
      ^ expected one of `...`, `..=`, `..`, `=>`, `if`, or `|`
expected one of `...`, `..=`, `..`, `=>`, `if`, or `|`, found `+`
unreachable expression
any code following this expression is unreachable
unreachable expression
let x = 1;
(match x {
    0 => 100,
    _ => 1000,
} + 1)
1001

The following match statement is problematic as y is an identifier pattern which is irrefutable. In another words, y will match anything and the branch _ => "are" will never be reached.

let x = 1;
fn f(x: i32) -> i32 {
    x
}
let y = f(1);
match x {
    y => "how",
    _ => "are",
}
"how"

Match Guards

You can use match guards to mimic an if/else or switch statement.

The following is a if/else like match statement even if it is not as concise.

let x = 1;
match x {
    v if v == 0 => "how",
    v if v == 1 => "are",
    _ => "you",
}
"are"
let x = 10;
match x {
    v if v == 0 => "how",
    v if v == 1 => "are",
    _ => "you",
}
"you"

Matching Literals

let x = 1;

match x {
    1 => println!("one"),
    2 => println!("two"),
    3 => println!("three"),
    _ => println!("anything"),
}

Matching Range

Destruct Struct and Matching

struct Pair {
    x: u32, 
    y: u32,
}
let p = Pair{x: 0, y: 1};
let Pair{x: v1, y: v2} = p;
v1
0
v2
1
let Pair{x: x1, y: x2} = Pair{x: 100, y: 200};
x1
100
x2
200