Rust Basic pattern matching


Example

// Create a boolean value
let a = true;

// The following expression will try and find a pattern for our value starting with
// the topmost pattern. 
// This is an exhaustive match expression because it checks for every possible value
match a {
  true => println!("a is true"),
  false => println!("a is false")
}

If we don't cover every case we will get a compiler error:

match a {
  true => println!("most important case")
}
// error: non-exhaustive patterns: `false` not covered [E0004]

We can use _ as the default/wildcard case, it matches everything:

// Create an 32-bit unsigned integer
let b: u32 = 13;

match b {
  0 => println!("b is 0"),
  1 => println!("b is 1"),
  _ => println!("b is something other than 0 or 1")
}

This example will print:

a is true
b is something else than 0 or 1