Code quality is one of the most important aspects of the programming world. It impacts our overall software quality and impacts how safe, secure, and reliable our codebase is.

Code quality is not only to perform efficiently but also to make code more readable.

In this article, we’ll try to get details of the matches macro, and we will also see the scenarios where we can incorporate this macro to improve our code quality.

matches macro!

_matches_(macro) is provided by Rust’s standard library and an external crate called matches.

Here we’ll talk about the matches macro provided by our standard library only, although both matches provide the same functionality but let’s focus on the official one.

So _matches_ checks whether the given expression matches any of the given patterns or not.

The return type of this macro is a boolean. It returns true if the provided pattern matches, false otherwise.

This macro makes our code cleaner and easy to read. In shot it improves code readability and quality.

Syntax
matches! (expression, pattern)

Let’s understand this syntax:

Here we have to provide two parameters, the expression, and pattern.

expression: a statement that evaluates to some value or some value,

pattern: any condition for which we want to check our expression

For example:

pub enum Test {
    FIRST,
    SECOND
}

fn is_first(data: Test) -> bool {
    matches!(data, Test::FIRST)

}

fn main() {
println!("{}", is_first(Test::FIRST))
}

Okay! now we get the idea in terms of the role of this macro and how to use it. Now let’s understand some internal behavior of this like, how it deals with things internally.

#rust #macros

Enhance Code Quality using `matches` Macro! in Rust
1.45 GEEK