In Rust, a macro_rules! macro generates newtype IDs such as UserId(u64); which fragment specifiers should capture the name, the inner type and the visibility?
answer
- the position in the output decides
- a struct name needs an identifier
- a field needs a whole type
- visibility may be empty
basics
~20 sCapture the name with ident, the wrapped type with ty and the visibility with vis, plus $(#[$attr:meta])* for attributes. Each specifier must produce what the output position needs: a struct name is an identifier, a field is a type.
solid answer
~40 sPick each fragment specifier by where the captured tokens land in the expansion. The struct name goes after `struct`, which needs an identifier, so use `$name:ident`; `$name:expr` fails with "expected identifier, found metavariable". The inner type is a field type, so use `$inner:ty`, which accepts `u64`, `Vec<String>` and `&'static str`; `ident` stops at the `<` of `Vec<String>` and `path` rejects `&'static str`. Use `$vis:vis`, which may match nothing and then leaves the struct private, and `$(#[$attr:meta])*` to forward attributes, doc comments included. `tt` would accept almost anything and push the error into the expansion. The macro can then generate `struct`, `impl From<$inner>` and `impl Display` for every ID in one repetition, and `stringify!($name)` turns the name into a string.
code
rust · 34 linesuse std::fmt;
macro_rules! id_types {
($( $(#[$attr:meta])* $vis:vis $name:ident($inner:ty); )*) => {
$(
$(#[$attr])*
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
$vis struct $name($inner);
impl From<$inner> for $name {
fn from(raw: $inner) -> Self { $name(raw) }
}
impl fmt::Display for $name {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}#{}", stringify!($name), self.0)
}
}
)*
};
}
id_types! {
/// A user account.
pub UserId(u64);
OrderId(u64);
pub(crate) SessionId(u128);
}
fn main() {
let u = UserId::from(7);
let o: OrderId = 7.into();
println!("{u} {o} {}", SessionId(1));
}go deeper
Know the common fragment specifiers by name, ident, ty, expr and tt, and that each matches a different kind of Rust syntax.
Choose specifiers by the output position, explain why $name:expr fails as a struct name and $inner:ident rejects Vec<String>, and use vis and meta to forward visibility and attributes.
Use specifiers as validation: early errors at the call site instead of confusing parse errors in the expansion, and know when tt is the right tool for forwarding rather than a shortcut.
Weigh a macro that stamps out ID types against a generic Id type with markers, considering error messages, documentation and how many distinct impls each ID really needs.
## The task A service has many IDs that are all integers underneath: users, orders, sessions. Wrapping each in its own **newtype** (`struct UserId(u64);`) makes the type checker reject passing an `OrderId` where a `UserId` belongs. Writing the struct plus its `From` and `Display` impls by hand for every ID is repetitive, which is exactly what a `macro_rules!` **repetition** removes. The design question is which **fragment specifier** to give each metavariable. ## The rule of thumb: the output position decides A fragment specifier both validates the caller's tokens and fixes what the captured piece is. Once captured as an `expr`, a fragment is an expression and can only go where an expression may go. So read the transcriber first, see what each position needs, then choose: - **`$name:ident`**: the name follows `struct`, so it must be an identifier. The Reference defines `ident` as an identifier or keyword other than `_`, a raw identifier such as `r#type`, or `$crate`. - **`$inner:ty`**: the wrapped value is a field type. `ty` matches any Rust type: `u64`, `Vec<String>`, `&'static str`, `[u8; 16]`. - **`$vis:vis`**: a possibly empty visibility qualifier: `pub`, `pub(crate)`, or nothing. - **`$(#[$attr:meta])*`**: zero or more attributes; `meta` matches the inside of an attribute, and doc comments reach the macro as `#[doc = "..."]` attributes, so they are forwarded too. ## What the wrong choice does Each failure below was compiled with rustc 1.99.1: | Matcher piece | Call | Result | |---|---|---| | `$name:expr`, used as `struct $name(...)` | `id_type!(UserId, u64)` | error: expected identifier, found metavariable | | `$inner:ident` | `id_type!(Tags, Vec<String>)` | error: no rules expected `<` | | `$inner:path` | `field!(&'static str)` | error: no rules expected `&` | | `$name:tt` | `id_type!(42, u64)` | error: expected identifier, found `42`, reported only after the macro has expanded | The `expr` case is worth understanding: the caller wrote a bare identifier, which is a valid expression, so matching succeeded. The failure comes afterwards, because an `expr` fragment is an opaque expression and a struct name must be an identifier token. The `tt` case accepts any single token tree, so the macro gives no early, targeted error; the parser complains about the expanded struct instead. ## The full macro ```rust macro_rules! id_types { ($( $(#[$attr:meta])* $vis:vis $name:ident($inner:ty); )*) => { $( $(#[$attr])* #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] $vis struct $name($inner); impl From<$inner> for $name { fn from(raw: $inner) -> Self { $name(raw) } } )* }; } ``` How it works: 1. The outer `$( ... )*` repeats one declaration per ID, each ending in a literal `;`. 2. Inside it, the nested `$(#[$attr:meta])*` repetition collects that ID's attributes; the transcriber replays them at the same nesting depth. 3. `$vis` can be empty, so `OrderId(u64);` produces a private struct while `pub UserId(u64);` produces a public one. 4. `$inner:ty` is followed by `)`, the end of a delimited group, which is always allowed. Had it been followed by a token such as `+`, the definition would be rejected: `ty` may only be followed by tokens like `=>`, `,`, `=`, `;`, `:`, `>`, `[`, `{`, `as` or `where`. ## Other specifiers you will meet - **`path`** matches a type path such as `std::collections::HashMap<K, V>`, but not references, slices or tuples. - **`literal`** matches a literal, optionally with a leading `-`. - **`block`** matches a `{ ... }` block; **`item`** a whole item; **`pat`** a pattern; **`lifetime`** a lifetime such as `'a`; **`stmt`** a statement without its trailing semicolon. - **`tt`** matches one token tree and is the tool for forwarding input you do not want to interpret yet. ## Limits to know On stable Rust a `macro_rules!` macro cannot build a new identifier from pieces, so `UserIdBuilder` cannot be derived from `UserId`; the caller passes every name the expansion needs. `stringify!($name)` goes the other way, turning the identifier into the string `"UserId"` for a `Display` impl. Whether a macro or a generic `Id<T>` with marker types is the better design is a question for the lessons on generics and typestate; this macro is the declarative way to stamp out several distinct types.
- Why not capture everything as tt to keep the macro flexible?`tt` accepts any single token tree, so `id_type!(42, u64)` matches and the mistake surfaces as a parse error inside the expansion instead of a "no rules expected" error at the call. Specific specifiers document the macro's grammar and validate input early. `tt` is the right choice when you must forward or re-match tokens, as an internal helper rule does.
- Can the macro also generate a UserIdBuilder type from the name UserId?Not with stable `macro_rules!`: it cannot concatenate identifiers into a new one. Either the caller passes the second name explicitly, for example `UserId, UserIdBuilder`, or the team reaches for a procedural macro, which builds identifiers in Rust code.
- Any fragment specifier works because the transcriber just pastes text
- ident is enough for the inner type, Vec<String> included
- path matches every type, references included
- A vis fragment must match at least pub
- macro_rules! can join two identifiers into a new name