Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

rust

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 ?
    }
  };
}
like image 875
dronte7 Avatar asked Nov 28 '19 08:11

dronte7


People also ask

What is the default option in a match case in Scala?

getList("instance").

What is a value matching pattern?

A pattern is built from constants, constructors, variables and type tests. Pattern matching tests whether a given value (or sequence of values) has the shape defined by a pattern, and, if it does, binds the variables in the pattern to the corresponding components of the value (or sequence of values).

How does pattern matching work?

Pattern Matching works by "reading" through text strings to match patterns that are defined using Pattern Matching Expressions, also known as Regular Expressions. Pattern Matching can be used in Identification as well as in Pre-Classification Processing, Page Processing, or Storage Processing.

What is pattern matching syntax?

Pattern matching is a technique where you test an expression to determine if it has certain characteristics. C# pattern matching provides more concise syntax for testing expressions and taking action when an expression matches.


1 Answers

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.

like image 89
Alexey Romanov Avatar answered Oct 06 '22 09:10

Alexey Romanov