Skip to content
On this page

宏3:exercises/macros/macros3.rs

题目

rust
// macros3.rs
//
// Make me compile, without taking the macro out of the module!
//
// Execute `rustlings hint macros3` or use the `hint` watch subcommand for a
// hint.

// I AM NOT DONE

mod macros {
    macro_rules! my_macro {
        () => {
            println!("Check out my macro!");
        };
    }
}

fn main() {
    my_macro!();
}

让代码顺利编译通过,但是不要把宏的定义从模块中取出。

题目解析

默认情况下,宏没有基于路径的作用域。但是如果该宏带有 #[macro_export] 属性,则相当于它在当前 crate 的根作用域的顶部被声明。

rust
mod macros {
    #[macro_export] 
    macro_rules! my_macro {
        () => {
            println!("Check out my macro!");
        };
    }
}

fn main() {
    my_macro!();
}

参考资料

Powered by VitePress