What does #[macro_use] mean?

I have a crate like this:

.
├── Cargo.toml
└── src
    ├── error.rs
    ├── worker.rs
    ├── lib.rs

In error.rs above, I defined a declarative macro foo using macro_rules!. Now I wanted to use macro foo in worker.rs.

After some research, I found that I only need to add the following line at the top of lib.rs:

#[macro_use]

And I did not need to add this to the foo definition itself, nor to worker.rs. But I don't know why.

My question is: what does #[macro_use] mean exactly? especially when it's at the top of lib.rs?

It has no meaning "at the top", but more specifically "right before mod error;" has meaning. By default macros are scoped to their module, but #[macro_use] will let it escape to the parent context, including all submodules from there.

See Macros By Example - The Rust Reference

2 Likes

By the way, #[macro_use] is now a bit obsolete, since classic pathing can be used with macros provided they get re-exported at their definition site; which has the advantage of being consistent with the rest of the language's items. For more info, see:

https://stackoverflow.com/a/67140319/10776437

1 Like

Thanks, this seems to be nicer. When I tried it, the macro works but cargo clippy reports a warning like this:

warning: this import is redundant
  --> src/error.rs:50:1
   |
50 | pub(crate) use foo;
   | ^^^^^^^^^^^^^^^^^^^^^ help: remove it entirely
   |
   = note: `#[warn(clippy::single_component_path_imports)]` on by default
   = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#single_component_path_imports

This warning seems not valid to me. Is this a clippy bug? or should I fix my code?

Well, did you try removing it?

It's a clippy false positive, yes, since their maintainers may not be aware of this very pattern.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.