liveBook · Manning

Macro recursion

As explained in Learn Rust in a Month of Lunches

Macro recursion is a macro-expansion technique in which a macro invokes itself to process or handle additional input.

Macro recursion is a macro-expansion technique in which a macro invokes itself to handle additional input. A recursive definition usually includes a base case that performs the work and other arms that call the macro again. section 22.3

Reducing several inputs to one base case

The `my_macro!` example accepts no input, one expression, or many expressions. The latter two arms invoke `my_macro!()` again, so every form reaches the empty-input arm, which prints “Let's print this.” section 22.3

macro_rules! write {
    ($dst:expr, $($arg:tt)*) => ($dst.write_fmt($crate::format_args!($($arg)*)))
}

Inspecting standard-library macro definitions helps reveal how one macro forwards captured input to another macro. section 22.3

How Learn Rust in a Month of Lunches covers it

How deep it goes
Shows recursive macro arms and a base case, but stops short of explaining the complete expansion process.
Examples
Uses my_macro!, write!, format_args!, and todo! to illustrate recursive calls, argument forwarding, and macro inputs.
What you can do after
Evaluate macro-recursive behavior by tracing input-matching arms toward the terminating expansion.
How it connects
Connects macro recursion with macro expansion, macro_rules!, token trees, and standard-library macros.

Also explained in

Compare how 2 books explain macro recursion →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Rust in a Month of Lunches. The section links point to the parts of the book it draws on.