Sub topic 9
Generating structs, functions, and impls
This chapter assumes you can write a macro_rules! macro with ident, ty, and expr fragments and a repetition such as $(...),*. It also assumes you know how struct, impl, and trait items work in plain Rust. Here you will use those pieces to make a macro produce whole items instead of expressions.
Macros in item position
A macro invoked at module level is in item position. Its expansion must be one or more items, such as structs, functions, or impl blocks. The rules from earlier chapters work the same way. Only the transcriber changes: it contains item syntax instead of an expression.
Generating a struct
This macro takes a name and a list of field: type pairs. It emits a struct with a Debug derive.
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 ident fragment holds the struct and field names. The ty fragment holds each field's type. The repetition $($field: $ty),* runs once per pair, and both variables advance together.
Generating an impl block
One invocation can emit several items. This version also writes an impl with one getter per field:
macro_rules! make_struct_with_getters {
($name:ident { $($field:ident : $ty:ty),* $(,)? }) => {
#[derive(Debug)]
struct $name {
$($field: $ty),*
}
impl $name {
$(
fn $field(&self) -> &$ty {
&self.$field
}
)*
}
};
}
make_struct_with_getters!(Config { port: u16, host: String });
fn main() {
let c = Config { port: 8080, host: String::from("localhost") };
println!("{} {}", c.host(), c.port());
}Both repetitions use $field and $ty, so each getter takes its name and return type from the same pair. A field and a method can share a name in Rust, so c.port() and c.port are both valid.
Generating functions
A caller-supplied ident can name a new function. Items are not hygienic, so the generated function is visible to the surrounding code:
macro_rules! make_adder {
($fname:ident, $n:expr) => {
fn $fname(x: i32) -> i32 {
x + $n
}
};
}
make_adder!(add_two, 2);
make_adder!(add_ten, 10);
fn main() {
println!("{} {}", add_two(1), add_ten(1));
}This prints 3 11.
Implementing a trait for many types
A common use is to avoid repeating the same impl for each type. The ty repetition drives the whole block:
trait Describe {
fn describe(&self) -> String;
}
macro_rules! impl_describe {
($($t:ty),+ $(,)?) => {
$(
impl Describe for $t {
fn describe(&self) -> String {
format!("{} {}", stringify!($t), self)
}
}
)+
};
}
impl_describe!(i32, f64, bool);
fn main() {
println!("{}", 7i32.describe());
println!("{}", true.describe());
}stringify!($t) turns the type tokens into a string literal, so this prints i32 7 and bool true.
Common errors
- Missing semicolon. A macro invoked with parentheses or brackets at module level needs a trailing
;. One invoked with braces does not. - Wrong fragment for a name. Use
identfor names andtyfor types. Anexprfragment cannot appear where an item name belongs. - Mismatched repetition depth. Variables used inside
$( ... )*must come from a repetition at the same depth. - Name collisions. Generated items live in the caller's module. Two invocations that produce the same name cause a normal duplicate-definition error.
Exercise
Write a macro make_consts! so that make_consts!(A = 1, B = 2,); expands to const A: i32 = 1; and const B: i32 = 2;. Which fragment specifiers do you need?
Show answer
Use ident for the name and expr for the value: macro_rules! make_consts { ($($name:ident = $val:expr),* $(,)?) => { $( const $name: i32 = $val; )* }; }. The $(,)? accepts the trailing comma, and the repetition inside the transcriber emits one const item per pair.