Rust Macro (With Examples)

Procedural Macros in Rust – A Handbook for Beginners

Procedural Macros - The Rust Reference

Macro Repetitions in Rust

Rust macro is also useful when we need to generate repetitive code. We can define a macro to accept arguments and repeat the generated code based on those arguments.

The macro_rules! macro supports repetition using the $(...)* syntax. The ... inside the parentheses can be any valid Rust expression or a pattern.

Here's an example that demonstrates macro repetition:

// A macro which uses repetitions
macro_rules! repeat_print {
    // match rule which matches multiple expressions in an argument
    ($($x:expr),*) => {
        $(
            println!("{}", $x);
        )*
    };
}

fn main() {
    // Call the macro with multiple arguments
    repeat_print!(1, 2, 3);
}

Output

1
2
3

Here, the macro repeat_print takes a single argument, ($($x:expr),*), which is a repeating pattern.

The pattern consists of zero or more expressions, separated by commas, that are matched by the macro. The star (*) symbol at the end will repeatedly match against the pattern inside $().

Untitled

The code inside the curly braces println!("{}", $x);, is repeated zero or more times, once for each expression in the list of arguments as it is wrapped around $(...)* in the body of the macro definition. The $x in the code refers to the matched expressions.

Each iteration of the generated code will print a different expression. Now, when we call repeat_print!(1, 2, 3); the macro will generate this code:

println!("{}", 1); // matches argument 1,
println!("{}", 2); // matches argument 2,
println!("{}", 3); // matches argument 3

Thus, this macro repeat_print! can print multiple expressions in a concise and convenient manner, without having to write out the println! macro every time.

Procedural macros

Types of Procedural Macros

Derive macros