Open In App

Rust – Switch Case

Last Updated : 19 Jul, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

Switch statement is basically nested if statement, though it does not support expression, it matches an int, string, or boolean data type variable with a given set of cases that are provided by the programmer. It is mainly used in a menu-driven program where the user selects which function they want to run. A switch case in Rust is achieved by the keyword match. Let’s see a few examples to see how it works.

1. Single Variable Matching:

Unlike C or Java, only the case corresponding to the match is executed, so we need not worry about fall through. Thereby saving our effort to write a break statement after each case. Default case, where no match is found, is handled by the case ‘_’ (underscore). There is something special in Rust, the cases can have more than one value. 

Example:

Rust




fn main() {
  let num=3;
  match num{
  1=>println!("One"),
  2=>println!("Two"),
  3=>println!("Three"),
  _=>println!("Rest of the number"),
  
}


Output

Three

2. Several Values in a single case:

Several values can be included in a single case by separating them via ‘|’.

Example:

Rust




fn main() {
  let num=2;
  match num{
  1|3|5|7|9=>println!("Odd"),
  2|4|6|8=>println!("Even"),
  _=>println!("Only one  digit allowed"),
  }
  
}


Output

Even

 It’s not the end we can also include a range of values in each case. 

3. Cases with an inclusive range:

 A range is inclusive in this case that means both the ends are also included.

Example:

Rust




fn main() {
  let num=19;
  match num{
  13..=19=>println!("Teenage"),
  _=>println!("Not Teenage"),
  }
  
}


Output

Teenage

4. Boolean match case:

As stated in the beginning we can also use boolean values to match cases, we will now go for it. One more thing is that match can be used in an expression.

Example:

Rust




fn main() {
  let head = false;
    let coin_side = match head{
        false => "tail",
        true => "head",
    };
    println!("Coin Side={}", coin_side)
}


Output

Coin Side=tail

5. String match case:

At last, we will see how strings are used in matches.

Example:

Rust




fn main() {
  let coin = "head";
    match coin{
        "head" =>println!("head"),
        "tail"=> println!("tail"),
        _=>println!("False coin"),
    };
}


Output

head


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads