Book: macro_use needs more examples

Created on 13 Jan 2017  路  4Comments  路  Source: rust-lang/book

I recently added a "macros" module to my crate which I started using within various unit tests I had written. I then tried to figure out exactly how to import or use those macros within other modules in the crate and had a difficult time figuring out exactly how I was supposed to do that.

I found this text in the macros section in the current book (the new book hasn't reached macros yet apparently):

https://doc.rust-lang.org/book/macros.html

If a module has the macro_use attribute, its macros are also visible in its parent module after the child鈥檚 mod item. If the parent also has macro_use then the macros will be visible in the grandparent after the parent鈥檚 mod item, and so forth.

This is my project structure:

crate/
  src/
    lib.rs
    macros/
      mod.rs
    foo/
      mod.rs

The problem was that I kept modifying foo/mod.rs thinking I needed to do an import of some kind or apply #[macro_use] somehow. So I kept doing things like this to foo/mod.rs:

#[macro_use]
use super::macros::*;

...which rustc kept complaining were unused directives, and I couldn't figure out why, since it didn't fail, I assumed I must just be using it wrong.

It wasn't until I stumbled upon this stackoverflow post that I suddenly realized what I needed to do:

http://stackoverflow.com/questions/29068716/how-do-you-use-a-macro-from-inside-its-own-crate

I then noticed this:

The accepted answer is correct, but for anyone else who finds this question in the future, I'd like to add that the order in which modules are loaded is important.

...and then realised that the resolution was very simple. I just needed to place this at the top of my lib.rs file:

#[macro_use]
pub mod macros;

...before mod foo;, etc..

In retrospect, I think what would have helped me the most is a visual example of the importance of ordering and the placement of the relevant directive.

Enhancement

Most helpful comment

Duplicated by #579

This seems to be a serious obstacle for newcomers...

All 4 comments

Great example!! You're correct that we haven't gotten to macros in the new book yet-- we've decided to introduce them briefly in an appendix for a variety of reasons. I think we can mention macro_use and show an example like this, though.

Duplicated by #579

This seems to be a serious obstacle for newcomers...

This is resolved for the second edition in https://github.com/rust-lang/book/pull/997.

997 was merged, so closing!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

istarus picture istarus  路  4Comments

devimc picture devimc  路  4Comments

drandreaskrueger picture drandreaskrueger  路  4Comments

elahn picture elahn  路  3Comments

rpjohnst picture rpjohnst  路  4Comments