Macro: put block in particular module

Is there a way to define a macro (either procedural or macro_rules!) where:

// can be any *.rs file in the crate
put_in_foobar {
  ... BLAH ...

ends up having the same effect as

// at root of crate in
mod foobar {
  ... BLAH ...

This is a followup to Use [crate/module]::*all_the_traits*; - #3 by drmason13

The goal here is that I want to wrap all the trait definitions so that they go into ::my_traits module at the crate root.


So the macro here is helping to identify all the paths to all the [desired] traits in your crate?

I don't think I recommend it, but it sounds like the sort of thing a procedural macro is capable of.

It gets messy because you can't guarantee the order that modules are compiled in, or something like that. I think cargo-aoc uses global state to track what's been seen by other proc macros somehow. I'm not familiar with the details, but I think that's what this is for.

Instead I'd recommend simply re-exporting, for example:

mod foo;
mod bar;

// Edit to add: this mod needs to be public!
pub mod my_traits {
    pub use foo::submodule::FooTrait;
    pub use foo::FooTrait2;
    pub use bar::BarTrait;

In the consuming crate:

use the_crate::my_traits::*;

Edit: got the pubs right in the end I think :smiley:

1 Like

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.