I am trying to use Rusts feature to conditionally compile a module in my crate and also use it only when a feature is enabled. The conditional compilation works fine when the feature is set, but refuses to compile when the feature is not set.
I use the same feature flag to conditionally import the module in my main so my assumption is that the module shouldn't be imported when the feature isn't used.
#[cfg(feature = "debug")]
pub mod k {
pub struct S { pub x: i32, pub y: i32}
}
And how I use it in main
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);
}
If I enable the feature via the --features
flag then it compiles as expected:
cargo build --features "debug"
Finished dev [unoptimized + debuginfo] target(s) in 0.08s
But when I do not pass the --features
it fails and my expectation is that it should skip the block with the cfg!
set.
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`.
This is how my Cargo.toml
looks like
[features]
default = []
debug = []
Can someone explain why this happens and a better way to conditionally compile such blocks of code ?