Introduction

How can we check if a value matches a particular Rust pattern without needing to extract or bind any part of that value? While if let expressions or standard match blocks are powerful tools for pattern matching, they typically involve extracting data. Furthermore, we can’t directly check against an enum variant’s initializer (like UserRole::Admin) as if it were a type, because it acts more like a function constructing the value. So, how do we perform a simple check elegantly?

Enter the std::matches! macro. Using this macro, we can perform boolean checks to see if a value conforms to a given pattern. Despite the versatility of the main match expression, sometimes we simply need a straightforward true/false result, and matches! provides exactly that.

Similar Posts

Loading similar posts...

Keyboard Shortcuts

Navigation
Next / previous item
j/k
Open post
oorEnter
Preview post
v
Post Actions
Love post
a
Like post
l
Dislike post
d
Undo reaction
u
Recommendations
Add interest / feed
Enter
Not interested
x
Go to
Home
gh
Interests
gi
Feeds
gf
Likes
gl
History
gy
Changelog
gc
Settings
gs
Browse
gb
Search
/
General
Show this help
?
Submit feedback
!
Close modal / unfocus
Esc

Press ? anytime to show this help