在“cfg”宏下使用条件编译模块

dyi*_*ynx 2 conditional-compilation rust

我想知道如何在宏下使用条件编译模块cfg!。我正在尝试这个:

pub fn f() { ... }

#[cfg(feature = "x")]
pub mod xmodule {
   pub fn f() { ... }
}

pub fn test() {
  if cfg!(feature = "x") {
    xmodule::f();
  } else {
    f();
  }; 
}
Run Code Online (Sandbox Code Playgroud)

当我使用 编译它时它工作正常cargo check --features x,但如果我不启用该功能,它会失败并出现以下错误:

use of undeclared type or module `xmodule`
Run Code Online (Sandbox Code Playgroud)

我是否做错了什么,或者编译不够智能,无法理解如果未设置该功能则不应使用该模块?

Frx*_*rem 6

虽然该#[cfg]属性将有条件地编译代码,cfg!但它给出了等效的布尔值(例如true,如果启用了某个功能,false否则)。所以你的代码基本上编译成:

pub fn test() {
  if false { // assuming "x" feature is not set
    xmodule::f();
  } else {
    f();
  }; 
}
Run Code Online (Sandbox Code Playgroud)

因此,即使只有一个分支运行过,两个分支仍必须包含有效代码。

要获得实际的条件编译,您可以执行以下操作:

pub fn test() {
  if false { // assuming "x" feature is not set
    xmodule::f();
  } else {
    f();
  }; 
}
Run Code Online (Sandbox Code Playgroud)

游乐场示例

或者您可以使用第三方宏,例如cfg-if

pub fn test() {
  #[cfg(feature = "x")]
  fn inner() {
    xmodule::f()
  }

  #[cfg(not(feature = "x"))]
  fn inner() {
    f()
  }

  inner();
}
Run Code Online (Sandbox Code Playgroud)

游乐场示例