Switch cases are in every popular programming language.
Rust does not have a switch case, But it has similar to a match
case.
the match is a control flow statement used to execute a matching code against multiple patterns.
It is similar to switch cases in other programming languages and equivalent to if-else condition expression.
Rust match
here is a Syntax
match variable{
case1=> statement1
case2=> statement2
_=> Default statement
}
the match is a keyword in Rust. the variable is of type int, boolean, string or enum. case1 and case2 are case statements that are executed when matching variables with cas1 values.
the default case is denoted by an underscore(_
).
there is no break required to exit from the matched case.
fn main() {
let day=1;
match day{
1=>println!("MONDAY"),
2=>println!("TUESDAY"),
3=>println!("WEDNESDAY"),
4=>println!("THURDSDAY"),
5=>println!("FRIDAY"),
6=>println!("SATURDAY"),
7=>println!("SATURDAY"),
_=>println!("INVALID DAY"),
}
}
Output
MONDAY
Let’s see some examples of a matching case.
Rust match case with string variable
This program explains how to use string variables in match statements.
In this example, Created a variable of the type String
You have matched with a string literal.
fn main() {
let str = String::from("welcome");
match str {
"welcome" => {
println!("Matched");
}
_ => {
println!("Not matched");
}
}
}
Output is compilation error mismatched types as String and literal type are not matched in rust.
To fix this, use str.as_str() trait to refer the data.
fn main() {
let str = String::from("welcome");
match str.as_str() {
"welcome" => {
println!("Matched");
}
_ => {
println!("Not matched");
}
}
}
Output:
Matched
How to use enum in match case
Enum is constants that can be used in match cases using enum values.
Here is an example program
enum WEEKEND {
SATURDAY,
SUNDAY,
}
fn main() {
let weekend = WEEKEND::SUNDAY;
match weekend {
WEEKEND::SUNDAY => println!("SUNDAY"),
WEEKEND::SATURDAY => println!("SATURDAY"),
_ => println!("NOT WEEKEND"),
}
}
How to use multiple values matched with match case?
In this example, multiple case values are joined using pipe operator(|). Here is an example program
fn main() {
let day = 3;
match day {
1 | 2 | 3 | 4 | 5 => println!("Weekday"),
6 | 7 => println!("Weekend"),
_ => println!("Invalid week"),
}
}
output:
weekday
How to use range notation with match case in Rust?
range of values are denoted by first..=last syntax and values are sequential numbers with a start as the first value, and end as the last value.
Here is a match range example
.
fn main() {
let day = 4;
match day {
1 ..= 5 => println!("Weekday"),
6 | 7 => println!("Weekend"),
_ => println!("Invalid week"),
}
}
Output:
weekday