Javatpoint Logo
Javatpoint Logo

Match Operator

The match operator allows us to compare a value against a series of patterns, and executes the code whenever the match is found. The patterns can be literal values, variable names, wildcards and many other things.

Let's understand the match operator through a simple example:

Output:

C language
C++ language
Java language
C# language

In the above example, Computerlanguage is a custom data type which consists of four variants are C, Cplus, Java, Csharp. The match operator matches the value of the language with the expressions given in the match operator block.

Matching with Option<T>

Option<T> is used when we want to get the inner value of T out of some case.

The Option<T> consists of two variants:

  • None: It indicates the failure or lack of value.
  • Some(value): It is a tuple struct that wraps the value with T.

Let's understand through an example:

Output:

2 is a even number
3 is a odd number

Matches are exhaustive

In Rust, matches are exhaustive, i.e., we should exhaust every possible case for the code to be valid. Suppose we forget to write the None case then the Rust compiler will show the bug that "pattern 'None' not covered".

Let's understand this case through an example:

Output:

Rust Enum Match Operator




Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials