DEV Community

Discussion on: Learning Rust - Understanding pattern matching

Collapse
 
deciduously profile image
Ben Lovy • Edited

Awesome write-up - i don't think it ever occurred to me to match on a range like that. Pattern matching is one of my favorite features in any language that offers it. I find myself using match extensively, almost excessively, and it pairs really well with enums for this reason.

The mandatory pattern that needs to be always present

If you use an enum, you must exhaustively match each variant, and if you avoid using _ as a catch-all when matching on an enum type, you can now fearlessly add functionality and just trust the compiler to walk you through each part of your code that needs to change! You can de-structure the variant right in the match arm, too:

match some_option {
    Some(value) => println!("{}", value),
    None => println!("Option contained no value!"),
}

My Rust projects tend to end up with a bunch of enum types that carry inner values and structs, not a pattern I'd been used to in any other language. Because of this, refactoring in Rust is fearless and super pleasant.

Collapse
 
brunooliveira profile image
Bruno Oliveira

Awesome stuff! I can't wait to get even more familiar with the language and its ecosystem and frameworks to start a larger project!

Collapse
 
deciduously profile image
Ben Lovy

Looking forward to reading about it !