DEV Community

Discussion on: Else Before If In Rust

Collapse
 
b0c1 profile image
b0c1

Ok, but why better it's than the pattern matching?

    let num = Some(4);

    match num {
        Some(x) if x < 5 => println!("less than five: {}", x),
        Some(x) => println!("{}", x),
        None => (),
    }

doc.rust-lang.org/book/ch18-03-pat...

So your example like this:

fn main() {
    let n = 11;
    let x = match n {
        10 => "unless case 1".to_string(),
        // Match several values
        11 => "unless case 2".to_string(),
        // Match an inclusive range
        _ => "normal case".to_string(),
    };

    println!("{}",x);
}
Collapse
 
louy2 profile image
Yufan Lou

The point is to promote the normal case to the top. In your code the normal case is at the bottom.

The merit of promoting the normal case to the top is it is more natural to read and write. It's a very subtle and subjective merit.

Collapse
 
b0c1 profile image
b0c1

Great, but disagree.
Usually, your "normal case" is the "fallback" method in the control statement, because the else statement is optional and not necessary.
Your normal case is unnatural, because:

  • you always expect a "normal" way
  • and when not run the normal way? you may need to check all condition
  • so you first need to skip the normal way and scroll down to all other condition

The try/catch "normal case" is different. In try/catch you will try to do something and if something wrong you create a fallback.

but this is only my opinion :D