Avatar ·

如何在多个Rust模块文件中使用宏?

你好!我正在学习Rust,在尝试将宏提取到单独模块时遇到了问题。我有一个项目,在`main.rs`中定义了一个有用的宏`my_println!`。我想在其他位于单独文件中的模块中使用它。 这是我的项目结构: ``` src/ main.rs utils/ mod.rs helper.rs ``` 在`main.rs`中我定义了宏: ```rust macro_rules! my_println { ($($arg:tt)*) => { println!("[LOG] {}", format!($($arg)*)); }; } mod utils; ``` 在`utils/mod.rs`中我声明了子模块: ```rust pub mod helper; ``` 在`utils/helper.rs`中我尝试使用宏: ```rust pub fn do_something() { my_println!("Hello from helper!"); } ``` 但编译器报错:`error: cannot find macro 'my_println' in this scope`。我了解到Rust中的宏不像函数那样默认导出。如何正确组织代码,使宏在项目的所有模块中可用?是否需要使用`#