我想知道如何使用cfg!
下的条件编译模块宏。我正在尝试这个:
pub fn f() { ... }
#[cfg(feature = "x")]
pub mod xmodule {
pub fn f() { ... }
}
pub fn test() {
if cfg!(feature = "x") {
xmodule::f();
} else {
f();
};
}
当我用
cargo check --features x
编译它时它工作正常,但如果我不启用该功能,它会失败并出现以下错误:use of undeclared type or module `xmodule`
我是做错了什么还是编译不够聪明,无法理解如果未设置该功能,则不应使用该模块?
最佳答案
而#[cfg]
属性将有条件地编译代码,cfg!
is 给出等效的 bool 值(例如 true
如果启用了某个功能,则 false
否则)。所以你的代码基本上编译成:
pub fn test() {
if false { // assuming "x" feature is not set
xmodule::f();
} else {
f();
};
}
因此,即使只运行了一个分支,两个分支仍必须包含有效代码。
要获得实际的条件编译,您可以执行以下操作:
pub fn test() {
#[cfg(feature = "x")]
fn inner() {
xmodule::f()
}
#[cfg(not(feature = "x"))]
fn inner() {
f()
}
inner();
}
Playground example
或者您可以使用第三方宏,例如
cfg-if
:use cfg_if::cfg_if;
pub fn test() {
cfg_if! {
if #[cfg(feature = "x")] {
xmodule::f();
} else {
f();
}
}
}
Playground example
关于rust - 在 `cfg` 宏下使用条件编译模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62350046/