RustPattern Matching


Syntax

  • _ // wildcard pattern, matches anything¹
  • ident // binding pattern, matches anything and binds it to ident¹
  • ident @ pat // same as above, but allow to further match what is binded
  • ref ident // binding pattern, matches anything and binds it to a reference ident¹
  • ref mut ident // binding pattern, matches anything and binds it to a mutable reference ident¹
  • &pat // matches a reference (pat is therefore not a reference but the referee)¹
  • &mut pat // same as above with a mutable reference¹
  • CONST // matches a named constant
  • Struct { field1, field2 } // matches and deconstructs a structure value, see below the note about fields¹
  • EnumVariant // matches an enumeration variant
  • EnumVariant(pat1, pat2) // matches a enumeration variant and the corresponding parameters
  • EnumVariant(pat1, pat2, .., patn) // same as above but skips all but the first, second and last parameters
  • (pat1, pat2) // matches a tuple and the corresponding elements¹
  • (pat1, pat2, .., patn) // same as above but skips all but the first, second and last elements¹
  • lit // matches a literal constant (char, numeric types, boolean and string)
  • pat1...pat2 // matches a value in that (inclusive) range (char and numeric types)

Remarks

When deconstructing a structure value, the field should be either of the form field_name or field_name: pattern. If no pattern is specified, an implicit binding is done:

let Point { x, y } = p;
// equivalent to
let Point { x: x, y: y } = p;

let Point { ref x, ref y } = p;
// equivalent to
let Point { x: ref x, y: ref y } = p;

1: Irrefutable pattern