The Match Statement
The statement can be used in place of long if..else if...else statement. It's much cleaner.
fn main(){
let my_num = 1;
match my_num {
0 => println!("it's zero"),
1 => println!("it's one"),
}
}
So, the code op there won't compile because the Rust compiler will expect that all possible situation is matched or it won't compile.
The match pattern is:
- match keyword
- match condition/text
- curly braces
- pattern
- pattern on the left, fat arrow and what to do when the pattern matches
- Each line is called an arm
- A comma to separate each arm
To account for every other possible match we can't react we use the underscore (_
) to say "Anything else?" do this ....
fn main(){
let my_num = 1;
match my_num {
0 => println!("it's zero"),
1 => println!("it's one"),
_ => println!("Some other number"),
}
}
-> Match can also be used to assign variables
fn main(){
let my_num = 1;
let second_number = match my_num {
0 => println!("it's zero"),
1 => println!("it's one"),
_ => println!("Some other number"),
};
}
Notice the semicolon after the match statement, it as if we wrote:
let second_number = 1;
-> Match can also be used for complicated patterns as well like tuples
fn main(){
let weather = "Rainy";
let condition = "Shower";
match (weather, condition) {
("Sunny", "Clear") => println!("it's sunny and pleasant today"),
("Rainy", "Shower")=> println!("it's rainy with dark clouds"),
_ => println!("Favourable"),
}
}
We can have an if statement in a match statement this is known as a match guard
fn main(){
let firstcolor = (234,45,4);
let secondcolor = (0,45,13);
let thirdcolor = (234,0,0);
match_color(firstcolor)
match_color(secondcolor)
match_color(thirdcolor)
}
fn match_color(rgb: (i32,i32,i32)){
match rgb{
(r,_,_) if r < 10 => println!("Not much red"),
(_,g,_) if g < 10 => println!("Not much green"),
(_,_,b) if b < 10 => println!("Not much blue"),
_ => println!("Each color is less than 10"),
}
}
The thirdcolor
shows that the match
statement always stops when it finds a match and it doesn't check the rest. A for
loop can assist this in working how we would have wanted.
-> Each arm
must return the same type if not the compiler will scream at us.
We can also use @
to give a name to the value of a match expression for use.
fn match_color(rgb: (i32,i32,i32)){
match rgb{
colors @ (r,_,_) if r < 10 => println!("Not much red {:?}", colors),
colors @ (_,g,_) if g < 10 => println!("Not much green {:?}", colors),
colors @ (_,_,b) if b < 10 => println!("Not much blue {:?}", colors),
_ => println!("Each color is less than 10"),
}
}