我正在尝试使用Rusts功能有条件地在我的箱子中编译模块,并且仅在启用功能时才使用它。设置功能后,条件编译可以正常工作,但未设置功能时,则拒绝编译。
我使用相同的功能标志有条件地将模块导入到我的主模块中,因此我的假设是当不使用功能时不应导入模块。
#[cfg(feature = "debug")]
pub mod k {
pub struct S { pub x: i32, pub y: i32}
}
我如何在主菜单中使用它
pub fn main() {
if cfg!(feature = "debug") {
use self::k;
let _s = k::S {x: 4, y: 5};
}
let g = vec![1, 2, 4];
println!("{:?}", g);
}
如果我通过--features
标志启用该功能,则它将按预期编译:
cargo build --features "debug"
Finished dev [unoptimized + debuginfo] target(s) in 0.08s
但是当我不通过--features
时,它会失败,并且我希望它应该跳过设置了cfg!
的代码块。
error[E0432]: unresolved import `self::k`
--> src/main.rs:32:13
|
32 | use self::k;
| ^^^^^^^ no `k` in the root
error: aborting due to previous error
For more information about this error, try `rustc --explain E0432`.
这就是我的Cargo.toml
的样子
[features]
default = []
debug = []
有人可以解释为什么会发生这种情况以及有条件地编译这种代码块的更好方法吗?