Rust Tutorial

Rust - Match Statement



The Match statement in Rust language is used to execute one of many code statements. It can be considered as group of If-else statements.

Syntax

match expression {
  case1 => {
    statement 1;
  }
  case2 => {
    statement 2;
  } 
     ...
     ...
     ...
  caseN => {
     statement N;
  }
  // default case 
  _ => {
     default statement;
   }
} 

The expression is evaluated and matched with the cases. When the case matches, the following block of code is executed. If no case matches with expression, the default code block gets executed.

Example:

In the example below, a variable called i with value 2 is matched against case values. When the case value matches with expression value, the following block of code gets executed.

fn main (){
  let i = 2;
  match i {
    1 => {println!("Red");}
    2 => {println!("Blue");} 
    3 => {println!("Green");}
    _ => {println!("No match found.");}
  }
}

The output of the above code will be:

Blue

default case

In Rust, the default case starts with _ followed by => and default code block. The default code block gets executed when the expression value do not match with any test cases.

Example:

In the example below, a variable called i with value 10 is matched against case values. As there is no case that matches with value 10, hence default block of code gets executed.

fn main (){
  let i = 10;
  match i {
    1 => {println!("Red");}
    2 => {println!("Blue");} 
    3 => {println!("Green");}
    _ => {println!("No match found.");}
  }
}

The output of the above code will be:

No match found.

Common code blocks

There are instances where same code block is required in multiple cases.

Example:

In the example below, same code block is shared for different match cases.

fn main (){
  let i = 10;
  match i {
    1 => {println!("Red");}
    2 | 10 => {println!("Blue");} 
    3..=5 => {println!("Green");}
    _ => {println!("No match found.");}
  }
}

The output of the above code will be:

Blue

Using if expressions in case statements

Scala gives the flexibility of using if expressions in case statements.

Example:

In the example below, the second, third and fourth case statements, all use if expressions to match ranges of numbers.

fn main (){
  let i = 50;
  match i {
    1 => {println!("Red");}
    i if i == 2 || i == 10 => {println!("Blue");} 
    3..=5 => {println!("Green");}
    i if i > 10 => {println!("Yellow");}
    _ => {println!("No match found.");}
  }
}

The output of the above code will be:

Yellow

5