锈蚀条件编译的其他情况

时间:2020-09-28 05:32:23

标签: rust

仅当没有cfg块匹配时,如何才能编译一些代码?例如这样的东西:

#IF NUM == 1
//something
#ELSE IF NUM == 2
// something
#ELSE
// no case match, panic!
#ENDIF

2 个答案:

答案 0 :(得分:2)

例如用手

#[cfg(thing1)]
// something
#[cfg(all(not(thing1), thing2))]
// something
#[cfg(all(not(thing1), not(thing2)))]
// no case

或者,在一个函数内并且如果在某些情况下都可以编译“东西”,则可以使用cfg!。由于它的计算结果为文字,因此优化程序很有可能会剔除不匹配的位:

if cfg!(thing1) {
    // something
} else if cfg!(thing2) {
    // something
} else {
    panic!();
}

尽管compile_error比恐慌更有意义。

还有a cfg-if crate符合人体工程学。

有关该主题的更多信息,请参见文章Yak shaving conditional compilation in Rust,该文章扩展并讨论了各种方法。

答案 1 :(得分:0)

您可以在not块的条件部分中使用cfg。您可以在文档中看到cfg

的示例
// This function only gets compiled if the target OS is linux
#[cfg(target_os = "linux")]
fn are_you_on_linux() {
    println!("You are running linux!");
}

// And this function only gets compiled if the target OS is *not* linux
#[cfg(not(target_os = "linux"))]
fn are_you_on_linux() {
    println!("You are *not* running linux!");
}

如果您需要更复杂的内容,也可以使用anyall,例如:

#[cfg(target_os="linux")]
fn get_os() -> &str { return "Linux"; }

#[cfg(target_os="windows")]
fn get_os() -> &str { return "Windows"; }

#[cfg(not(any(target_os="linux", target_os="windows")))]
fn get_os() -> &str { return "Unknown"; }

reference中提供了更多详细信息。

相关问题