Rust Macros
Rust macros (Macros) are a powerful tool for generating code at compile time, allowing you to create custom syntax extensions when writing code.
A macro (Macro) is a technique for metaprogramming (Metaprogramming) in code, allowing code generation at compile time. Macros can help simplify code, improve readability and maintainability, while allowing developers to perform some code-generation operations at compile time.
There are two types of macros in Rust: declarative macros (Declarative Macros) and procedural macros (Procedural Macros).
This article focuses on declarative macros.
Macro definition
In Rust, the macro_rules! keyword is used to define declarative macros.
macro_rules! my_macro {
// Pattern matching and expansion
($arg:expr) => {
// Generated code
// Use $arg to replace the matched expression
};
}
Declarative macros are defined using the macro_rules! keyword; they are called "macro_rules" macros. This kind of macro definition is based on pattern matching, which can match the structure of code and generate corresponding code based on the matched pattern. Such macros can simplify some common code patterns without introducing new syntactic structures.
Below is a simple example of a macro definition:
Example
// Macro definition
macro_rules
!
greet
{
// Pattern matching
(
$name
:
expr
)
=>
{
// Macro expansion
println
!
(
"Hello, {}!"
,
$name
)
;
}
;
}
fn
main
(
)
{
// Invoke the macro
greet
!
(
"World"
)
;
}
Description
- **Pattern matching:** A macro matches the code fragments passed to it through pattern matching; a pattern is the left-hand side of a macro rule, used to capture different code structures.
- **Rules:** Macro rules are a set of patterns introduced by $ and corresponding expansion code, with rules separated by semicolons.
- ** Macro expansion:** When a macro is invoked, the matched pattern is replaced by the corresponding expansion code, which is the right-hand side of the macro rule.
Example
Below is a more complex example demonstrating how to use a macro to create a simple vec! macro for more convenient Vec creation:
Example
// Macro definition
macro_rules
!
vec
{
// Base case, the empty case
(
)
=>
{
Vec
::
new
(
)
}
;
// Recursive case, the case with elements
(
$
(
$element
:
expr
)
,+
$
(
,
)
?
)
=>
{
{
let
mut
temp_vec
=
Vec
::
new
(
)
;
$
(
temp_vec.push
(
$element
)
;
)
temp_vec
}
}
;
}
fn
main
(
)
{
// Invoke the macro
let
my_vec
=
vec
!
[
1
,
2
,
3
]
;
println
!
(
"{:?}"
,
my_vec
)
;
// Output: [1, 2, 3]
let
empty_vec
=
vec
!
[
]
;
println
!
(
"{:?}"
,
empty_vec
)
;
// Output: []
}
In this example, the vec! macro uses pattern matching, as well as syntax like $($element:expr),+ $(,)?) to capture the elements passed to the macro and create a Vec from them.
Note that $(,)?) is used to handle a trailing comma, so it works in different usage contexts.
Procedural Macros
Procedural macros are a more flexible and powerful kind of macro, allowing manipulation of the abstract syntax tree (AST) through custom code-generation processes at compile time. Procedural macros are functionally closer to functions, but they are more complex to write and use.
Types of procedural macros:
- Derive Macros: used to automatically implement traits (such as
Copy、Debug) for you. - Attribute Macros: used to attach extra metadata to declarations, such as
#[derive(Debug)]。
Implementing procedural macros usually requires using features provided by the proc_macro library, such as TokenStream and TokenTree, to manipulate source code more directly.