Where pattern matching is used

We’ve talked about the use of match and if let statements, but we didn’t get into the details: Virtually every branch of match and if let is followed by a pattern, which can be used in a variety of expressions to deconstruct data.

Patterns in the Match branch

Here is the syntax for match expressions, none of which start with a pattern:

match VALUE {
  PATTERN => EXPRESSION,
  PATTERN => EXPRESSION,
  PATTERN => EXPRESSION,
}
Copy the code

The match expression must exhaust all possibilities for an exhaustive match value:

let value: Result<i32.String> = Ok(5);
match value { // When reporting an error, all possibilities must be exhausted
  Ok(v) => println!("{}", v),
}

// Add Err condition
match value {
  Ok(v) => println!("{}", v),
  Err(s) => println!("{}", s)
}
/ / 5
Copy the code

Patterns in if let conditional expressions

Use the code after the let keyword as a pattern to match “=” the data after the sign. Unlike match, if let does not need to exhaust all cases, and else if let and else branches are optional:

let favorite_color: OptionThe < &str> = None;
let is_tuesday = false;
let age: Result<u8, _ > ="34".parse();

if let Some(color) = favorite_color {
  println!("Use your favorite color, {}, as the background color.", color);
} else if is_tuesday {
  println!("Tuesday is green!");
} else if let Ok(age) = age {
  if age > 30 {
    println!("Use purple as a background color.");
  } else {
    println!("Use orange as the background color."); }}else {
  println!("Use blue as the background color.");
}
// Use purple as the background color
Copy the code

The match takes effect in new curly braces:

if let Ok(a) = age {
  if a > 30 { // a is available
    println!("Use purple as a background color."); }}// Error: a is not available
if let Ok(a) = age && a > 30 {
  // a is available
}
Copy the code

The pattern in the while let conditional loop

Similar to if let, when a match succeeds after the let keyword, while continues until the match fails:

let mut stack = vec![1.2.3];
// Take one at a time from the back of the stack until it does not fit
while let Some(top) = stack.pop() {
  println!("{}", top);
}
/ / 3
/ / 2
/ / 1
Copy the code

Patterns in the for loop

The pattern followed by the for keyword matches the data following the in keyword:

let v = vec!['a'.'b'.'c'];
for (index, value) in v.iter().enumerate() {
  println!("{} is at index {}", value, index);
}
// a is at index 0
// b is at index 1
// c is at index 2
Copy the code

Patterns in let statements

The let keyword used to declare variables also does pattern matching:

let PATTERN = EXPRESSION;
Copy the code

Matching a single value:

let v = 5;
Copy the code

Matching tuples:

let (x, y, z) = (1.2.3);
Copy the code

The schema must have the same number of elements as the data:

let (x, y) = (1.2.3); // Error: 3 elements expected, 2 elements found
Copy the code

Patterns in function arguments

Function parameters are used as patterns to match the data passed in when the function is called, matching a single value:

fn foo(x: i32) {}
Copy the code

You can also deconstruct tuples:

fn print_position(&(x, y): &(i32.i32)) {
  println!("({}, {})", x, y); / / (3, 5)
}
let point = (3.5);
print_position(&point);
Copy the code

Cover: Follow Tina to draw America

Read more about the latest chapter on our official account