Declarative Macros

Learn about declarative macros, a powerful feature for code generation and abstraction.

Declarative macros in Rust, often referred to as “macros by example” or simply “macros,” are a powerful feature that allows you to define custom syntax extensionsCode that adds further functionality to the language.. Declarative macros work by pattern matching on the source code and transforming it based on predefined patterns.

We’ve been using declarative macros up until now but now we’ll delve into learning how they’re made and can be used. For example, we’ve used the println! and vec! macros to print something on the screen and create vectors without having to go through the hassle of initializing the vector and individually populating it with elements. Another example is that of the format! macro, which takes an expression and converts it into String type.

This is why any repetitive tasks can be translated into macros, which can save a lot of time.

Creating declarative macros

Let’s look at how we can create a very basic macro. We need to use the macro_rules! keyword if we want to tell Rust that we’re about to create a macro. Their definition is a lot like match statements. We’re supposed to pass in some input, known as captures, and expect some kind of operational function as a result. When referring to macros, a capture, since it is similar to a match statement’s pattern matching, refers to the input that the macro is supposed to take. These placeholders are matched against actual code passed to the macro, allowing the macro to process and transform the input. The types of input we pass into the macro can be of different types. Let’s have a look at how we can handle captures that are of type expression (expr).

Get hands-on with 1400+ tech skills courses.