Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
751 views
in Technique[技术] by (71.8m points)

rust - Is there a way to use the cfg(feature) check on multiple statements?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...