Skip to content

Rewriting if-else conditionals as match statements

Rewriting if-else conditionals as match statements

Devdutt Shenoi
Apr 28, 20202 min read

t 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"); 
}

Run in playground

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"),
}

Run in playground

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"),
}

Run in playground

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!

Did you enjoy this article?

Recommend it — Standard Reader surfaces well-loved writing to more readers across the network.

Across the AtmosphereDiscussions