I need to define many types in one file (->submodule) each and expose them all on the same level of the module. This creates lots of repetitive overhead in the mod.rs:
mod foo;
mod bar;
mod baz;
[...]
pub use self::foo::*;
pub use self::bar::*;
pub use self::baz::*;
[...]
I tried to fix this with a macro, but it does not compile:
macro_rules! expose_submodules {
( $( $x:expr ),* ) => {
$(
mod $x;
pub use self::$x::*;
)*
};
}
yields
error: expected identifier, found `foo`
--> src/mod.rs:4:17
|
4 | mod $x;
| ^^ expected identifier
|
::: src/mod.rs:10:1
|
2 | expose_submodules![foo, bar, baz];
| ----------------------------------------------------------------- in this macro invocation
|
= note: this error originates in the macro `expose_submodules` (in Nightly builds, run with -Z macro-backtrace for more info)
(same issue when passing the parameters as strings).
How would I best fix this macro or do the whole task in more idiomatic rust?
To fix the macro you need to use ident
fragment instead of expr
:
macro_rules! expose_submodules {
( $( $x:ident ),* ) => {
$(
mod $x;
pub use self::$x::*;
)*
};
}