基本模式匹配

// 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")
}

如果我們不覆蓋每個案例,我們將得到編譯器錯誤:

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

我們可以使用 _ 作為預設/萬用字元案例,它匹配所有內容:

// 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")
}

這個例子將列印:

a is true
b is something else than 0 or 1