Ben Chuanlong Du's Blog

It is never too late to learn.

Pattern Matching in Rust

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

In [ ]:
: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.

In [3]:
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
In [9]:
let x = 1;
(match x {
    0 => 100,
    _ => 1000,
} + 1)
Out[9]:
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.

In [4]:
let x = 1;
fn f(x: i32) -> i32 {
    x
}
let y = f(1);
match x {
    y => "how",
    _ => "are",
}
Out[4]:
"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.

In [5]:
let x = 1;
match x {
    v if v == 0 => "how",
    v if v == 1 => "are",
    _ => "you",
}
Out[5]:
"are"
In [6]:
let x = 10;
match x {
    v if v == 0 => "how",
    v if v == 1 => "are",
    _ => "you",
}
Out[6]:
"you"

Matching Literals

In [ ]:
let x = 1;

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

Matching Range

Destruct Struct and Matching

In [2]:
struct Pair {
    x: u32, 
    y: u32,
}
In [4]:
let p = Pair{x: 0, y: 1};
In [5]:
let Pair{x: v1, y: v2} = p;
In [7]:
v1
Out[7]:
0
In [8]:
v2
Out[8]:
1
In [9]:
let Pair{x: x1, y: x2} = Pair{x: 100, y: 200};
In [10]:
x1
Out[10]:
100
In [11]:
x2
Out[11]:
200
In [ ]:

Comments