Sub topic 3
Generating structs, functions, and impls
Assume basic Rust syntax, Cargo, modules, and pub. A declarative macro can generate items such as structs, functions, and impl blocks. This avoids repeating the same source pattern while keeping the generated code type-checked.
Generating related items
macro_rules! make_record {
($name:ident { $($field:ident: $ty:ty),* $(,)? }) => {
#[derive(Debug)]
struct $name {
$($field: $ty),*
}
impl $name {
fn new($($field: $ty),*) -> Self {
Self { $($field),* }
}
}
};
}
make_record!(Point { x: i32, y: i32 });
fn main() {
let point = Point::new(3, 4);
println!("{point:?}");
}Here, ident matches a name and ty matches a type. The repetition emits one field and one constructor parameter for each input field.
Scoping, exporting, and `$crate`
A macro defined in a module follows macro visibility rules. #[macro_export] exports a macro_rules! macro at the crate root:
#[macro_export]
macro_rules! call_helper {
($value:expr) => {
$crate::helper($value)
};
}
pub fn helper(value: i32) -> i32 {
value + 1
}$crate refers to the defining crate, even when another crate invokes the macro. This avoids assuming that the caller imported the helper under a particular name.
Recursive macros and internal rules
A recursive macro can consume one token tree at a time:
macro_rules! count {
() => { 0usize };
($head:tt $($tail:tt)*) => {
1usize + count!($($tail)*)
};
}
fn main() {
println!("{}", count!(red green blue));
}An internal rule gives helper behavior a private-looking convention:
macro_rules! log_value {
(@format $value:expr) => {
println!("value = {:?}", $value)
};
($value:expr) => {
log_value!(@format $value)
};
}The @format arm is an implementation detail, not true access control.
Inspecting expansions and choosing alternatives
Use cargo expand to inspect generated Rust when available. Errors such as “no rules expected this token” usually mean that no matcher arm accepts the invocation's token sequence. Check separators, fragment types, and optional commas first.
macro_rules! cannot freely analyze types or inspect arbitrary syntax. Use a procedural macro when you need custom parsing, generated code based on type information, or attributes with complex behavior. Use a function when ordinary runtime parameters are enough.
Exercise
Which fragment specifier should match a caller-supplied struct name?
Show answer
Use ident, because the name is an identifier.