If you've ever written a long if/else chain and thought "there must be a cleaner way" — match is Rust's answer. It lets you check a value against a list of patterns and run different code for each one.
By the end of this post, you'll understand exactly how match works, why Rust forces you to use it a certain way, and how it handles real-world things like errors.
What is match ?
match compares a value against a list of patterns . The first matching pattern wins, and the code next to it runs.
Here's the simplest example — matching a number:
let number = 2 ;
match number { 1 => println! ( "One" ), 2 => println! ( "Two" ), 3 => println! ( "Three" ), _ => println! ( "Something else" ), } // Output: Two
Enter fullscreen mode
Exit fullscreen mode
Each pattern => code pair is called an arm .…