Skip to main content

Pattern Match

Not only match, let is also using pattern match. This is why let Some(i) = expression works. Partterns are used in:

  • let declarations
  • Function and closure parameters
  • match expressions
  • if let expressions
  • while let expressions
  • for expressions
let x = 9;
let message = match x {
0 | 1 => "not many",
2 ..= 9 => "a few",
_ => "lots"
};

struct S(i32, i32);

match S(1, 2) {
S(z @ 1, _) | S(_, z @ 2) => assert_eq!(z, 1),
_ => panic!(),
}

Match guards:

let message = match maybe_digit {
Some(x) if x < 10 => process_digit(x),
Some(x) => process_other(x),
None => panic!(),
};

if-let and let-else

ref:

ref:

Cheatsheet

// v: Vec<i32>
match v.first() {
Some(i) if *i <= 5 => println!("it's {}", i),
Some(..) => println!("Default clause"),
None => (),
}

Questions

What is the difference between '..' and '_' in a pattern match
  • .. in pattern is used to denote several elements in list context. Ref
  • _ is just a placeholder. Ref
Patterns in rust
  • literal pattern
  • identifier pattern
  • wildcard pattern
  • rest pattern
  • range pattern
  • reference pattern
  • struct pattern
  • tuple pattern
  • slice pattern
  • or pattern