How do I use a macro across module files?

前端 未结 4 1957
隐瞒了意图╮
隐瞒了意图╮ 2020-11-27 13:56

I have two modules in separate files within the same crate, where the crate has macro_rules enabled. I want to use the macros defined in one module in another m

4条回答
  •  猫巷女王i
    2020-11-27 14:20

    I have came across the same problem in Rust 1.44.1, and this solution works for later versions (known working for Rust 1.7).

    Say you have a new project as:

    src/
        main.rs
        memory.rs
        chunk.rs
    

    In main.rs, you need to annotate that you are importing macros from the source, otherwise, it will not do for you.

    #[macro_use]
    mod memory;
    mod chunk;
    
    fn main() {
        println!("Hello, world!");
    }
    

    So in memory.rs you can define the macros, and you don't need annotations:

    macro_rules! grow_capacity {
        ( $x:expr ) => {
            {
                if $x < 8 { 8 } else { $x * 2 }
            }
        };
    }
    

    Finally you can use it in chunk.rs, and you don't need to include the macro here, because it's done in main.rs:

    grow_capacity!(8);
    

    The upvoted answer caused confusion for me, with this doc by example, it would be helpful too.

提交回复
热议问题