liveBook · Manning

Identifier fragment specifier

As explained in Write Powerful Rust Macros

An identifier fragment specifier matches an identifier token as an input fragment in a Rust declarative macro.

An identifier fragment specifier, written as `ident`, matches an identifier token supplied to a Rust declarative macro. It is useful when a macro needs a type, struct, or other named item while generating the remaining code itself. section 2.2.3

Generating a newtype method

The `generate_get_value` macro captures a struct name with `$struct_type:ident`, inserts that name into an `impl` block, and generates `get_value`. Calls such as `generate_get_value!(FirstName);` and `generate_get_value!(LastName);` reuse the same implementation pattern. section 2.2.3

The matcher captures only the item name; the generated method, return type, and field access remain fixed unless additional fragments are accepted. A second matcher can capture a return type with `ty`, allowing the same macro to support both `String` and `i32` newtypes. section 2.2.3

macro_rules! ??? {
    ??? => {
        impl $something {
            fn hello_world(&self) {
                println!("Hello world")
            }
        }
    };
}

struct Example {}
hello_world!(Example);

fn main() {
    let e = Example {};
    e.hello_world(); // prints "Hello world"
}

Complete the matcher and transcriber so a macro accepts an identifier such as `Example` and generates its `hello_world` method. section 2.4

How Write Powerful Rust Macros covers it

How deep it goes
Explains identifier-token matching through a working macro and contrasts it with adding a `ty` fragment for return types.
Examples
Uses `FirstName`, `LastName`, `Age`, and `Pay` with a generated `get_value` method.
What it assumes
Assumes familiarity with Rust structs, `impl` blocks, methods, and basic `macro_rules!` matcher-transcriber syntax.
What you can do after
Build declarative macros that accept struct or type names and emit implementations using those captured identifiers.
How it connects
Connects `ident` with declarative macros, `macro_rules!`, matchers, transcribers, newtypes, and type fragments.

Also explained in

Compare how 2 books explain identifier fragment specifier →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Write Powerful Rust Macros. The section links point to the parts of the book it draws on.