The matches! macro is a built-in Rust utility that checks if a value matches a specific pattern, returning true or false without requiring explicit variable binding. It is the idiomatic way to perform simple pattern matching checks when you only care about the boolean result and not the extracted values.
Use matches! instead of writing a verbose match expression or an if let block when you need a quick boolean check. It is particularly useful for validating Option states, checking enum variants, or verifying slice contents.
Here is a practical example checking an Option and an enum:
fn main() {
let value: Option<i32> = Some(42);
let status = Status::Active;
// Check if value is Some without binding the inner integer
if matches!(value, Some(42)) {
println!("Value is exactly 42");
}
// Check enum variant
if matches!(status, Status::Active | Status::Pending) {
println!("Status is valid");
}
// Contrast with a full match (more verbose for simple checks)
let is_some = match value {
Some(_) => true,
None => false,
};
}
enum Status {
Active,
Pending,
Inactive,
}
You can also use it with guards or complex patterns, though readability may decrease if the pattern becomes too intricate. For example, checking a tuple or a slice:
let point = (1, 2);
let data = vec![1, 2, 3];
// Check tuple structure
assert!(matches!(point, (1, _)));
// Check slice length and content
assert!(matches!(data, [1, .., 3]));
The macro is preferred over if let when you don't need to destructure the value into a variable for later use. If you need to use the matched value, if let or match is more appropriate. matches! keeps your code clean by avoiding unnecessary scope blocks and variable bindings for simple truth checks.
Remember that matches! is a macro, not a function, so it handles pattern matching at compile time. It works with any type that supports pattern matching, including custom structs, enums, and standard library types. It is available in Rust 1.42 and later, making it a standard tool in modern Rust codebases for concise conditional logic.