pub 使用/一次“导出”许多子模块

问题描述 投票:0回答:1

我需要在一个文件(->子模块)中分别定义多种类型,并将它们全部暴露在模块的同一级别上。这会在 mod.rs 中产生大量重复开销:

mod foo;
mod bar;
mod baz;
[...]

pub use self::foo::*;
pub use self::bar::*;
pub use self::baz::*;
[...]

我尝试用宏修复此问题,但它无法编译:

macro_rules! expose_submodules {
    ( $( $x:expr ),* ) => {
        $(
            mod $x;
            pub use self::$x::*;
        )*
    };
}

产量

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)

(将参数作为字符串传递时也会出现同样的问题)。

我如何最好地修复这个宏以更惯用的生锈方式完成整个任务?

rust macros export macro-rules
1个回答
0
投票

要修复宏,您需要使用

ident
片段而不是
expr
:

macro_rules! expose_submodules {
    ( $( $x:ident ),* ) => {
        $(
            mod $x;
            pub use self::$x::*;
        )*
    };
}
© www.soinside.com 2019 - 2024. All rights reserved.