Macro for crate + full module path?

Are there macros that will return, as string:

  • crate name
  • full module path


For crate name, I found this solution (which feels a bit hacky as it depends on ENV variables) Getting the using crate's name from within a library

Are there other solutions ?

For crate name, this is the way.


suppose we have:


and suppose the module hierarchy is sane, if the macro is invoked in,
I'd respect a name of foo::bar::blah

On nightly, I think you can use a proc-macro to grab the "span" of some Rust code. The span (on nightly) will give you a SourceFile. You can, with some effort, figure out the full module path from this.
Not sure if there are nicer methods for this.

1 Like

For the crate name, the canonical way to get it is with env!("CARGO_PKG_NAME"). Cargo guarantees certain environment variables will always be provided, so it's not a hacky solution.

For the current module path, does the std::module_path!() macro work for you?

This way is much simpler than using a custom proc-macro and will have less impact on build times.


Tiny nit: note that this gives the package name, which may have hyphens, and technically doesn't have to match the crate name (even if instances of this are very rare).

There is also env!("CARGO_CRATE_NAME"), but I don't remember exactly when it is available (I remember running into it not being available sometimes)


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.