Rust’s pattern matching feels simple enough: match on enums, destructure tuples, handle Option and Result. I stuck with these basics for months because, well, they work. But there’s a whole world of pattern techniques I wasn’t using. Once I discovered what’s actually possible, I kicked myself for all the verbose code I’d written.Here’s what advanced pattern matching can look like (don’t worry if you don’t understand it now):It took me way too long to discover these techniques. This post is so you don’t have to. I’ll cover:The basics (plus hidden details)Advanced techniques that matterBest practices I learned the hard wayLet’s start with the fundamentals.If you’re already comfortable with basic pattern matching, feel free to skim this section.The simplest patterns match exact values or capture anything:This example shows:Literal matching (200)Or patterns for multiple values (301 | 302 | 307 | 308)Range matching (500..=599)Variable binding (code)Wildcard (_) to ignore the valuePattern matching shines when breaking apart compound data:Key points:.. ignores remaining fields you don’t care aboutPatterns are checked top-to-bottom, so active: false catches inactive users firstYou can match on array and slice structure:Notice the difference: The array match requires exactly 5 elements, while slice patterns adapt to any length. The .. matches however many elements are between the specified positions.ShareTime for the fun stuff. These techniques will make your code beautiful and a joy to write.By default, pattern matching moves values, like this:When we match Some(s), Rust transfers ownership of the String to variable s. This leaves data partially moved since the Option wrapper exists but its contents are gone. Rust prevents using partially moved values.But you can work with references using two approaches below.First approach: Match on a referenceNotice the match is on &data, Rust automatically borrows the inner fields for you.Second approach: Use refYou can achieve the same...
First seen: 2025-09-30 23:39
Last seen: 2025-09-30 23:39