Sub topic 9
Generating structs, functions, and impls
This chapter assumes you can write macro_rules! rules with fragment specifiers and repetitions, and that you know how a transcriber builds output. Here you will use those tools to generate items: structs, functions, and impl blocks. Item-generating macros remove repetitive boilerplate that generics and traits cannot express.
Macros in item position
A macro can be invoked wherever Rust expects an item, such as at module level or inside an impl block. The expansion must then be a sequence of valid items. The macro can emit several items at once, so one invocation can define a struct and its impl together.
One syntax rule matters at the module level. An invocation with parentheses or brackets must end with ;. An invocation with braces must not need one.
macro_rules! make_struct {
($name:ident { $($field:ident : $ty:ty),* $(,)? }) => {
#[derive(Debug)]
struct $name {
$($field: $ty),*
}
};
}
make_struct!(Point { x: i32, y: i32 });
fn main() {
let p = Point { x: 1, y: 2 };
println!("{:?}", p);
}The matcher uses $name:ident for the struct name. It uses $field:ident : $ty:ty inside a comma-separated repetition for the fields. The transcriber repeats $field: $ty once per matched pair. The program prints Point { x: 1, y: 2 }.
The same repetition variables can appear more than once in a transcriber. Each use repeats in lockstep, as long as the variables were captured at the same repetition depth.
From invocation to generated items
Passing through attributes and visibility
The first version hard-codes #[derive(Debug)] and gives the struct private visibility. A more useful macro lets the caller decide. Two fragment specifiers handle this:
metamatches the contents of an attribute, such asderive(Debug, Clone).vismatches a visibility qualifier. It can match nothing, so a missingpubis valid.
The macro below forwards both, then adds a constructor in an impl block:
macro_rules! make_struct {
(
$(#[$meta:meta])*
$vis:vis struct $name:ident {
$($fvis:vis $field:ident : $ty:ty),* $(,)?
}
) => {
$(#[$meta])*
$vis struct $name {
$($fvis $field: $ty),*
}
impl $name {
$vis fn new($($field: $ty),*) -> Self {
Self { $($field),* }
}
}
};
}
make_struct! {
#[derive(Debug, Clone)]
pub struct Point {
pub x: i32,
pub y: i32,
}
}
fn main() {
let p = Point::new(1, 2);
println!("{:?}", p.clone());
}This prints Point { x: 1, y: 2 }. A few points about how it works:
$(#[$meta:meta])*accepts zero or more attributes. The caller can add doc comments too, because///comments are attributes.$visis reused for the constructor, so apub structgets apub fn new.- The field identifiers serve double duty. They name the struct fields, the constructor parameters, and the shorthand initializers in
Self { x, y }. - The caller supplied the identifiers
xandy, so hygiene does not hide them. The parameters and the shorthand fields all refer to the same names.
Generating functions
A macro can create a family of similar functions. The caller supplies each function name as an ident:
macro_rules! unit_converters {
($($fn_name:ident : $factor:expr),* $(,)?) => {
$(
fn $fn_name(value: f64) -> f64 {
value * $factor
}
)*
};
}
unit_converters! {
km_to_m: 1000.0,
m_to_cm: 100.0,
}
fn main() {
println!("{} {}", km_to_m(2.5), m_to_cm(1.5));
}The output is 2500 150. Because the caller chose km_to_m and m_to_cm, both functions are visible in main.
Generating trait implementations
Implementing one trait for many types is the most common use of item-generating macros. The standard library does this for the integer types, and you can do the same:
trait Describe {
fn describe(&self) -> String;
}
macro_rules! impl_describe {
($($t:ty => $label:expr),* $(,)?) => {
$(
impl Describe for $t {
fn describe(&self) -> String {
format!("{} {}", $label, self)
}
}
)*
};
}
impl_describe! {
i32 => "int",
f64 => "float",
bool => "bool",
}
fn main() {
println!("{}", 5i32.describe());
println!("{}", 2.5f64.describe());
println!("{}", true.describe());
}The output is int 5, float 2.5, and bool true. The body calls format! with self, so each type must implement Display. That requirement is checked after expansion, once per generated impl. If you add a type without Display, the compiler reports the error against the expanded code, which can be confusing.
A generic impl<T: Display> Describe for T would be simpler here. It is also less flexible. Choose a macro when the implementations differ in ways generics cannot express, such as different method bodies per type, or when you must implement a foreign trait for many concrete types and the blanket impl would conflict with coherence rules.
Choosing fragment specifiers for items
| Piece of the item | Specifier | Notes |
|---|---|---|
| Struct, function, or field name | `ident` | Caller's name stays visible after expansion |
| Field type or return type | `ty` | Matches generics such as `Vec<u8>` as one unit |
| Attributes | `meta` inside `#[...]` | Wrap it in `$(#[$meta:meta])*` |
| `pub`, `pub(crate)`, or nothing | `vis` | Can match empty, so no `?` needed |
| Default value or constant | `expr` | Matches one full expression |
| Whole item to pass through | `item` | Matches any complete item |
| Lifetime parameter | `lifetime` | Matches `'a` |
The item specifier is useful for wrapper macros that modify or decorate existing definitions. A macro such as with_logging! { fn foo() {} } can capture $i:item and re-emit it with extra code around it.
Hygiene and generated items
Hygiene applies to local variables and labels. It does not apply to items. A function, struct, or trait that the macro writes by name, without taking the name from the caller, is visible at the call site:
macro_rules! define_helper {
() => {
fn helper() -> i32 {
7
}
};
}
define_helper!();
fn main() {
println!("{}", helper());
}This prints 7. Two invocations of define_helper!() in the same module would define helper twice, which is a compile error. This is why item macros usually take names from the caller.
Local variables inside generated function bodies are still hygienic. A let binding in the macro's body cannot capture or shadow a variable that the caller passed in as an expr.
Common errors
- Missing semicolon.
make_struct!(Point { x: i32 })at module level with no;gives "macros that expand to items must be delimited with braces or followed by a semicolon". Add the;or switch to braces. - Duplicate definitions. Invoking an item macro twice with the same names produces "the name is defined multiple times". Name collisions are your responsibility.
- Mismatched repetition depth. Using
$fieldoutside any$(...)*in the transcriber, or at a different depth than it was captured, gives "variable 'field' is still repeating at this depth". Align your repetitions with the captures. - Specifier mismatch. Writing
$t:identfor a type likeVec<u8>fails with "no rules expected the token<". Usetyfor types. - Trailing comma rejected. A matcher without
$(,)?rejectsPoint { x: i32, }even though normal Rust allows the trailing comma.
Exercise
Extend the item-generating macro impl_describe! so that the caller can also give each type a custom prefix without changing the trait. Which fragment specifier would you use for the prefix string, and why does $t:ty => $label:expr still match when the caller writes Vec<u8> => "bytes"?
Show answer
Keep $label:expr for the prefix. An expr fragment matches any single expression, including a string literal, and it can be followed by ,. The type Vec<u8> is matched by ty as one unit, including its angle brackets, and ty can be followed by =>, so the arm accepts it. The generated impl Describe for Vec<u8> also needs Vec<u8>: Display, which does not hold. The macro matches, but compilation of the expansion then fails. To support such types, take the formatting expression from the caller instead of calling format! on self directly.
Exercise
A macro takes $name:ident and you want it to define both a struct $name and a function new_$name. Why can't you write that, and what are two ways around it?
Show answer
macro_rules! has no way to join tokens into a new identifier, so new_$name is parsed as the token new_ followed by $name, which is not valid. One workaround is to have the caller pass both names, for example make!(Point, new_point). The other is to use the paste crate, which provides paste::paste! and lets you write [<new_ $name:snake>] to build the identifier.