Is there a way to use the cfg(feature) check on mu

2020-02-01 03:53发布

Is there a way to minimize the following feature check?

#[cfg(feature = "eugene")]
pub mod eugene_set_steam_id;
#[cfg(feature = "eugene")]
pub mod eugene_balance;
#[cfg(feature = "eugene")]
pub mod eugene_force_map;
#[cfg(feature = "eugene")]
pub mod eugene_rating;
#[cfg(feature = "eugene")]
pub mod eugene_stat;
#[cfg(feature = "eugene")]
pub mod eugene_steam_id;
#[cfg(feature = "eugene")]
pub mod eugene_top;

To something like:

#[cfg(feature = "eugene")] {
    pub mod eugene_set_steam_id;
    pub mod eugene_balance;
    pub mod eugene_force_map;
    pub mod eugene_rating;
    pub mod eugene_stat;
    pub mod eugene_steam_id;
    pub mod eugene_top;
}

This would better convey meaning and be more ergonomic.

标签: rust
2条回答
够拽才男人
2楼-- · 2020-02-01 04:17

The cfg-if crate provides the cfg-if! macro that should do what you want:

#[macro_use]
extern crate cfg_if;

cfg_if! {
    if #[cfg(feature = "eugene")] {
        pub mod eugene_set_steam_id;
        pub mod eugene_balance;
        pub mod eugene_force_map;
        pub mod eugene_rating;
        pub mod eugene_stat;
        pub mod eugene_steam_id;
        pub mod eugene_top;
    } else {
    }
}

In fact, it even describes itself using your words:

A macro to ergonomically define an item depending on a large number of #[cfg] parameters. Structured like an if-else chain, the first matching branch is the item that gets emitted.

查看更多
▲ chillily
3楼-- · 2020-02-01 04:21

You could create a private module that import all the files, and then let the parent module re-export everything from that private module:

#[cfg(feature = "eugene")]
#[path = ""]
mod reexport_eugene_modules {
    pub mod eugene_set_steam_id;
    pub mod eugene_balance;
    pub mod eugene_force_map;
    pub mod eugene_rating;
    pub mod eugene_stat;
    pub mod eugene_steam_id;
    pub mod eugene_top;
}

#[cfg(feature = "eugene")]
pub use reexport_eugene_modules::*;

You still need to write that #[cfg] line twice though.

查看更多
登录 后发表回答