Match in Rust Programming

Rust ProgrammingServer Side ProgrammingProgramming

Rust provides us with a match keyword that can be used for pattern matching. It is similar to the switch statement in C, and the first arm that matches is evaluated.

Example

Consider the example shown below −

fn main() {
   let number = 17;
   println!("Tell me about {}", number);
   match number {
      1 => println!("One!")
      2 | 3 | 5 | 7 | 11 => println!("A prime"),
      13..=19 => println!("A teen"),
      _ => println!("Ain't special"),
   }
}

In the above example, we are trying to use a match against a number and just like a normal switch, we are matching the variable against different arms, and the one that matches the value will be evaluated.

Output

Tell me about 17
A teen

A match can also be used as an expression.

Example

Consider the example shown below −

 Live Demo

fn main() {
   let boolean = true;
   let bin = match boolean {
      false => 0,
      true => 1,
   };
   println!("{} -> {}", boolean, bin);
}

Output

true -> 1
raja
Published on 03-Apr-2021 13:07:52
Advertisements