Open In App

Rust – Switch Case

Last Updated : 23 Apr, 2024
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


Similar Reads

Rust vs C++ - Will Rust Replace C++ in Future
We have seen many programming languages trending according to their functionality and popularity but languages are not meant to be used according to their popularity. We should consider the overall efficiency and productivity when it comes to using a programming language. Speaking of efficiency and popularity one of the most used programming langua
6 min read
Rust - A Case of Safe Concurrency
Before looking at Rust itself, let's go back to 1992. Guido van Rossum, in an attempt to tackle race condition in CPython interpreter, added a lock famously known as the Global Interpreter Lock or GIL for short. Two and a half decades later, this was one of the main shortcomings for the Python interpreter we all love and use. So what is the Global
5 min read
Rust - Bounds
In Rust, we have a concept of Bounds. Bounds are used in situations when we are working with generics and are trying to figure out the nature and type of parameters that are required for stipulating the functionality that the type in Rust implements. Syntax: fn gfg <T: GeeksforGeeks>(x: T) { println!(" {}", x); //more methods defined} In the
2 min read
Rust lifetime Constructor
In Rust, we have a concept of a lifetime constructor that falls under the ownership category. Rust enforces a certain set of rules through its concept of ownership and lifetimes. In this article, we would be learning more about Lifetimes in Rust. In Rust, there are various regions that are present in the code which are generally complex and referre
3 min read
Rust - Casting
Type Conversion or casting in Rust is a way to convert one type to another. As its name suggests, type conversion is the process of converting variables from one data type to another. So that, the compiler treats the variable as a new datatype. Rust doesn't allow us to implicitly convert the datatype between primitive types. The primitive types are
3 min read
Rust - Struct Visibility
In Rust, there is a concept of Struct Visibility. Generally, the items present in the module have visibility that is private by nature but we can override the private items by usage of the public ('pub') modifier. Public items of the module are accessed outside the module scope and the visibility in these scenarios is not very high. To avoid this s
3 min read
Rust - If let Operator
The basic difference between conventional if-else and if let is that if let uses one pattern that needs to be matched to an expression also known as scrutinee, if the pattern matches the expression then the corresponding code is executed, or in most cases that value is assigned according to it. Syntax : let gfg=value; let gfg_answer=if let value_1
2 min read
Rust - Reference Counted Smart Pointer
In Rust, there is a concept of a Smart pointer where we use multiple ownership explicitly using the Rc<T> type. This Rc <type> is referred to as Reference counting. This concept was introduced in Rust to handle scenarios where a single value of the variable has multiple owners. Rc<T> keeps how many references are made to a value a
2 min read
Rust - Crate_type Attribute
In Rust, we have a concept of crates. Crates are basically libraries or packages as defined in other programming languages. Cargo, the rust package management tool helps ship the crates of our program to other programs' cargo. Crates produce an executable library where every crate has a root module that has the code for the crate. The crate_type at
2 min read
Rust Basics
In the last 2 decades, computers and the internet have made an increasing demand, and with the evolution of new technologies, devices, and protocols the programming languages are also being updated regularly but still most of the early programming languages like C, and C++ have shown some drawbacks. These drawbacks motivated others to create new pr
5 min read
Article Tags :