File tree Expand file tree Collapse file tree 1 file changed +39
-0
lines changed Expand file tree Collapse file tree 1 file changed +39
-0
lines changed Original file line number Diff line number Diff line change @@ -357,6 +357,45 @@ fn main() {
357
357
358
358
[ items ] : ../reference.html#items
359
359
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
+
360
399
# Further reading
361
400
362
401
The [ advanced macros chapter] [ ] goes into more detail about macro syntax. It
You can’t perform that action at this time.
0 commit comments