Macro Design · 18 min · free with an account

Macro Hygiene

Lesson preview · about 30%

Resolve generated names without accidental capture.

Core idea

Rust macros track syntax context so identifiers introduced by a macro do not casually collide with names at the call site.

Start with the idea

Rust macros track syntax context so identifiers introduced by a macro do not casually collide with names at the call site. Use explicit paths such as $crate for helper items exported with a macro.

A macro can introduce identifiers in the caller's scope, and those names must resolve predictably. Rust's syntax contexts protect many identifiers introduced by a declarative macro from accidentally capturing a similarly named local value. This is hygiene, but it is not a reason to ignore names entirely: exported macros still need a stable way to refer to helper items from their defining crate. $crate::helper points to that crate even when a caller renames its dependency.

Keep learning, for free

The rest of this lesson is waiting for you.

Create a free account to read the complete explanation, see the infographic, explore the code, and try the exercises. All 742 lessons and algorithm steps are included.

No payment details. Your account opens the complete Academy.

← All lessons in Macros & Systems Rust