Menu

1 / 2

Understanding the match Keyword in Rust with Examples

DEV Community·Syeed Talha·6 months ago
#r53yYNbb
#matching#example#match#value#println
Reading 0:00
15s threshold

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 .…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.