Skip to content

Commit 65e1e6b

Browse files
author
Keegan McAllister
committed
Add a section on recursive macros
1 parent 0bd1565 commit 65e1e6b

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

src/doc/trpl/macros.md

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -357,6 +357,45 @@ fn main() {
357357

358358
[items]: ../reference.html#items
359359

360+
# Recursive macros
361+
362+
A macro's expansion can include more macro invocations, including invocations
363+
of the very same macro being expanded. These recursive macros are useful for
364+
processing tree-structured input, as illustrated by this (simplistic) HTML
365+
shorthand:
366+
367+
```rust
368+
# #![allow(unused_must_use)]
369+
macro_rules! write_html {
370+
($w:expr, ) => (());
371+
372+
($w:expr, $e:tt) => (write!($w, "{}", $e));
373+
374+
($w:expr, $tag:ident [ $($inner:tt)* ] $($rest:tt)*) => {{
375+
write!($w, "<{}>", stringify!($tag));
376+
write_html!($w, $($inner)*);
377+
write!($w, "</{}>", stringify!($tag));
378+
write_html!($w, $($rest)*);
379+
}};
380+
}
381+
382+
fn main() {
383+
# // FIXME(#21826)
384+
use std::fmt::Write;
385+
let mut out = String::new();
386+
387+
write_html!(&mut out,
388+
html[
389+
head[title["Macros guide"]]
390+
body[h1["Macros are the best!"]]
391+
]);
392+
393+
assert_eq!(out,
394+
"<html><head><title>Macros guide</title></head>\
395+
<body><h1>Macros are the best!</h1></body></html>");
396+
}
397+
```
398+
360399
# Further reading
361400

362401
The [advanced macros chapter][] goes into more detail about macro syntax. It

0 commit comments

Comments
 (0)