unegare
unegare

Reputation: 2579

How to access the matched value in the default case of pattern matching?

the question is about the default case.

Let's consider the following code:

fn func(x: i64) {
  match x {
    0 => println!("Zero"),
    1 => println!("One"),
    _ => {
      //How to get the value here not via repeating the matched expression ?
    }
  };
}

Upvotes: 30

Views: 10112

Answers (1)

Alexey Romanov
Alexey Romanov

Reputation: 170735

Assuming you don't want to repeat the expression because it's more complex than just a variable, you can bind it to a variable:

fn func(x: i64) {
  match <some complex expression> {
    0 => println!("Zero"),
    1 => println!("One"),
    y => {
      // you can use y here
    }
  };
}

This also works as a default case, because a variable pattern matches everything just like _ does.

_ is useful exactly when you don't want to use the value.

Upvotes: 35

Related Questions