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
