liveBook · Manning

Matcher-transcriber pair

As explained in Write Powerful Rust Macros

A matcher-transcriber pair is a declarative macro rule consisting of an input matcher and its corresponding output transcriber.

A matcher-transcriber pair is one declarative macro rule: the matcher describes accepted input, and the transcriber emits the corresponding Rust code. Write the two sides around an arrow inside macro_rules!, such as ($struct_type:ident) => { ... };. section 2.1.1

Keep these syntax rules in mind:

  • Delimit both matcher and transcriber with (), {}, or []; omitting the transcriber’s delimiters produces a confusing parse error. section 2.1.1
  • Separate multiple pairs with semicolons; the final pair may omit its semicolon. section 2.1.1
  • Choose one consistent delimiter style, with parentheses suggested as a practical default. section 2.1.1

Generating a typed accessor

A single pair can generate a method for a named struct: macro_rules! generate_get_value { ($struct_type:ident) => { impl $struct_type { pub fn get_value(&self) -> &String { &self.value } } }; } generate_get_value!(FirstName); A second pair can accept a type override, allowing the same macro to support non-String fields: macro_rules! generate_get_value { ($struct_type:ident) => { generate_get_value!($struct_type, String); }; ($struct_type:ident, $return_type:ty) => { impl $struct_type { pub fn get_value(&self) -> &$return_type { &self.value } } } } The first rule delegates to the more general second rule, reducing duplicated expansion logic. section 2.2.3

How Write Powerful Rust Macros covers it

How deep it goes
Defines delimiters, arrows, semicolons, fragment kinds, multiple rules, and recursive delegation, but not macro expansion internals.
Examples
Uses accessor generation for FirstName, LastName, Age, and Pay, including String and i32 return types.
What it assumes
Assumes familiarity with Rust structs, impl blocks, functions, references, and types while teaching macro rule syntax.
What you can do after
Build repetitive Rust implementations with macro_rules! using specialized and generalized matcher-transcriber pairs.
How it connects
Connects declarative macros with pattern matching, newtypes, impl blocks, identifiers, and Rust types.

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.