Macros defined in submodules?


#1

Hi there,

I cannot seem to get macros defined in submodules to work.

Here is my app structure:

Cargo.toml
src/
    main.rs
    app/
        util/
            mod.rs
            macros.rs
            traits.rs
        mod.rs

I tried all the possible combinations of #[macro_use], but main.rs never gets visibility on my macro.

main.rs:

#[macro_use]
use app::util::macros;

app/mod.rs

#[macro_use]
pub mod util;

app/util/mod.rs

pub mod traits;
#[macro_use]
pub mod macros;

app/util/macros.rs

#[macro_use]
macro_rules! hashmap {
    ($( $key: expr => $val: expr ),*) => {{
         let mut map = ::std::collections::HashMap::new();
         $( map.insert($key, $val); )*
         map
    }}
}

What did I do wrong? (I read the doc, and also multiple SO threads, still no luck)

Thank you in advance

Best regards,


#2

In main.rs you never actually tell rustc that the app directory exists.

If you replace main.rs with the following you will be able to use the macro.

#[macro_use]
mod app;

Remember, #[macro_use] can only be used with mod or extern crate, not use.

For example, if you want to use macros from a seperate crate, you could write

#[macro_use]
extern crate regex;

Here is a more complete guide on macros: https://doc.rust-lang.org/book/macros.html


#3

Hi neon,

Sorry, I did not write all my main.rs code, but I actually did do mod app; before useing the submodules.

However, it was indeed the only place where I did not put #[macro_use] (must be the exhaustion, because I have been at it for almost 1h and it’s very late here)

I changed that, and it works!! Well, except for an another unrelated error, but that I could fix without too much hassle.

Thank you for your help Neon! With all the Rustaceans kind help, I believe I may be able to understand the basics of Rust enough to successfully use Rust as the webserver for our application! And I’m all excited about this idea! :smile: (even though some people tend to discourage it, but whatever, I like Rust spirit)

Best regards,


#4

Glad to be of assistance. I was just clicking around the forums trying to get help with my own issue and I spotted this and thought it should be solvable.


#5

Well, good luck with your issues then (I’m afraid I won’t be of much help), but thanks again for the help, I was already in bed and jumped out of it to test your solution, and I’m glad I did :slight_smile: Thanks!