It is common in computing, to come across a conditional statement that contains a lot of ANDs, ORs and more. With rust-lang's powerful match
statement, a programmer can easily convey the message, let's see how.
match
statements takes pattern matching to another level. Using the simple syntax, one can also achieve what nested/ladder if
-else
blocks could. Here is a sample if
-else
code block.
if year%4 == 0 {
if year%100 != 0 || year%400 == 0 {
println!("Leap Year");
} else {
println!("Not a Leap Year");
}
} else {
println!("Not a Leap Year");
}
The above program can be rewritten with match
where patterns of boolean valued triples that are descriptive of conditions where the algorithm should print "Leap Year".
match (year%4 == 0, year%100 == 0, year%400 == 0) {
(_, _, true) => println!("Leap Year"),
(true, false, _) => println!("Leap Year"),
_ => println!("Not a Leap Year"),
}
You can rewrite the above program by combining the patterns that are indicative of the conditions being right for printing "Leap Year", thus decreasing the number of lines in the program.
match (year%4 == 0, year%100 == 0, year%400 == 0) {
(_, _, true) | (true, false, _) => println!("Leap Year"),
_ => println!("Not a Leap Year"),
}
So, that's a pretty simple intro to how match
works in rust, but there's a lot more to it than this, we'll discuss that later!
Here's a shorter one: