The macro system

Rust supports a macro system that has evolved quite a lot over the years. A distinctive feature of Rust macros are that they are guaranteed to not refer to identifiers outside their scope by accident, and so the macro implementation in Rust is hygienic. As one would expect, Rust macros are expanded to source code ahead of the compilation in place, and are compiled with the translation unit. The compiler enforces scoping rules on expanded macros to make them hygienic. Rust macros differ from other constructs in that they always end in an exclamation mark !.

Modern Rust has two ways of working with macros; the older, syntactic macro way, and the newer, procedural macro way. Let's look at each of these:

Get Network Programming with Rust now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.