match expressions

The match keyword is used to match a value against one or more patterns. In that sense, it works like a series of if let expressions:

  1. fn main() {
  2. match std::env::args().next().as_deref() {
  3. Some("cat") => println!("Will do cat things"),
  4. Some("ls") => println!("Will ls some files"),
  5. Some("mv") => println!("Let's move some files"),
  6. Some("rm") => println!("Uh, dangerous!"),
  7. None => println!("Hmm, no program name?"),
  8. _ => println!("Unknown program name!"),
  9. }
  10. }

Like if let, each match arm must have the same type. The type is the last expression of the block, if any. In the example above, the type is ().

See pattern matching for more details on patterns in Rust.

  • Save the match expression to a variable and print it out.
  • Remove .as_deref() and explain the error.
    • std::env::args().next() returns an Option<String>, but we cannot match against String.
    • as_deref() transforms an Option<T> to Option<&T::Target>. In our case, this turns Option<String> into Option<&str>.
    • We can now use pattern matching to match against the &str inside Option.