Macros

Macros are a method of using code to write code. They can be used to extend Rust with extra syntactical parts (such as the variable number of arguments in ), make writing lots of duplicate code easier (e.g. macros are used to generate the identical methods of the primitive integer types in std), or to create entirely different sub-languages within Rust (e.g. inline-python).

There are two types of macro in Rust: declarative macros and procedural macros, or proc-macros. Declarative macros are defined using, and provide a simple method of substituting a macro invocation for code. Procedural macros have to be defined in their own crate, and allow any arbitrary Rust code to run which will transform Rust code into different Rust code. Procedural macros are far more powerful, but are more difficult to write and slow down the compilation process (as they have to be both compiled and run during the compilation process).

Declarative Macros
Declarative macros are defined with. They use a -like syntax to determine which "branch" to use. Here is a simple macro that takes no arguments and expands to the string literal "Hello World!":

This macro has one arm which takes no arguments. Attempting to call the macro with an argument will result in an error as no arms match. Its body is delimited with braces, which aren't included in the expansion. The trailing semicolon is optional for the last match arm, but is required for all other match arms.

It can be invoked in three ways:


 * Using parenthesis:
 * Using brackets:
 * Using braces:

All three are completely equivalent, and whichever one is used is up to the user. There are conventions, however; function-like macros such as  are written with parenthesis (like a function call), array-like macros such as   are written with brackets (like an array literal) and macros that take in larger blocks of code are written with braces (like code blocks).

Any code written in the parameters of a macro will only be accepted if it matches exactly (excluding whitespace); for example  will match   and   but not   or. To accept variable parameters to the macro use a dollar sign, followed by the variable's name, followed by a colon, followed by the variable's type; for example,  will accept any expression and bind it to the variable. Then, in the body of the macro  will be expanded to the expression given to the macro. The following types are available:

Repeats
Declarative macros can specify parts to be repeated multiple times, by writing  where   is one of ,   or. specifies that the area should be repeated zero or one times,  specifies zero or more and   specifies one or more. Any token can be placed before the suffix to cause that token to have to appear in between each repeat. Using these features, a common pattern to allow trailing commas is.

In the body of the macro the same rules apply to expand the repeated variables. The source code of the  macro can be approximated using this: