基本模式匹配

// 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