簡體   English   中英

DRY for Rust 條件編譯帶特性

[英]DRY for Rust conditional compilation with features

我的圖書館有幾個功能,比如F1F2F3F4 ,.. 一次只能激活其中一個。 這些特征進一步分為類型ABC ,例如,特征F1F2屬於類型AF3F4屬於類型B等等。

我有幾次這樣的代碼(在庫中)

#[cfg(any(feature = "F1", feature = "F2"))]
fn do_onething_for_type_A(... ) {
// repeating same cfg predicate as above
#[cfg(any(feature = "F1", feature = "F2"))]
fn do_another_thing_for_type_A(... ) {
#[cfg(any(feature = "F3", feature = "F4"))]
fn do_onething_for_type_B(... ) {

有沒有辦法簡潔地編寫上述cfg謂詞,這樣我就不必在#[cfg(any(..一個新功能,比如F5類型,比如A ,我必須將行#[cfg(any(feature = "F1", feature = "F2"))]的出現更新為#[cfg(any(feature = "F1", feature = "F2", feature = "F5"))]

我的第一個想法是根據該功能創建一個屬性,然后使用如下屬性,但似乎我不能這樣做。

#[cfg(any(feature = "F1", feature = "F2"), typeA)]
#[cfg(any(feature = "F3", feature = "F4"), typeB)]

#[typeA]
fn do_onething_for_type_A(... ) {...}

#[typeA]
fn do_another_thing_for_type_A(... ) {

#[typeB]
fn do_onething_for_type_B(... ) {

為類型ABC聲明一個新特性是我最后的選擇。

您可以使用cfg_aliases crate,盡管它需要添加構建腳本。

// Cargo.toml
[build-dependencies]
cfg_aliases = "0.1.0"
// build.rs
use cfg_aliases::cfg_aliases;

fn main() {
    // Setup cfg aliases
    cfg_aliases! {
        type_a: { any(feature = "F1", feature = "F2") },
        type_b: { any(feature = "F3", feature = "F4") },
        type_c: { feature = "F5" },
    }
}
#[cfg(type_a)]
fn do_onething_for_type_A(... ) {...}

#[cfg(type_a)]
fn do_another_thing_for_type_A(... ) {

#[cfg(type_b)]
fn do_onething_for_type_B(... ) {

或者,您可以像 Tokio 那樣定義宏。

macro_rules! cfg_type_a {
    ($($item:item)*) => {
        $(
            #[cfg(any(feature = "F1", feature = "F2"))]
            $item
        )*
    }
}
cfg_type_a! {
    fn do_onething_for_type_A() {
        ...
    }
}
cfg_type_b! {
    fn do_onething_for_type_B() {
        ...
    }
}

請注意,基於宏的方法可能會給使用 CLion IDE 的庫的任何用戶帶來麻煩。 使用 IDE 時,您必須啟用

設置 > 語言和框架 > Rust > 擴展聲明性宏:使用實驗引擎

為上面定義的宏后面定義的東西獲取類型完成。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM