What Is Macro Hygiene in Rust?

Macro hygiene in Rust prevents naming conflicts between macro-generated code and the surrounding scope by treating identifiers as unique.

Macro hygiene in Rust is a compiler mechanism that prevents macros from accidentally capturing or conflicting with variables defined in the calling code. It ensures that identifiers generated inside a macro are treated as distinct from those in the surrounding scope, avoiding name collisions. This is managed automatically by the compiler using Span and Hygiene attributes, so you rarely need to configure it manually.

// Example: Hygiene prevents 'x' in the macro from shadowing 'x' in main
macro_rules! print_x {
    () => {
        let x = 42; // This 'x' is hygienic and won't conflict
        println!("Macro x: {}", x);
    };
}

fn main() {
    let x = 10; // This 'x' is safe from the macro
    print_x!(); // Prints: Macro x: 42
    println!("Main x: {}", x); // Prints: Main x: 10
}