I realized that doing something like the following does not work in Rust as it throws temp
not found error, because it seems the braces around #[cfg(not(feature = "my-feature"))]
create a new scope, right?:
fn main() {
#[cfg(not(feature = "my-feature"))] {
let temp: usize = 1;
}
let mut output = 0;
#[cfg(not(feature = "my-feature"))]
output = temp + 1;
println!("output: {:?}", output);
}
But what's the proper way then to enclose multiple lines with a feature flag in Rust without introducing a new scope (i.e., to re-use the existing variables later)?
You can use/abuse the fact that blocks are expressions to write something like this.
#[cfg(stuff)]
let (x, y, z) = {
let x = ...;
let y = ...;
let z = ...;
(x, y, z)
}
let mut output = 0;
#[cfg(stuff)]
println!("{x}, {y}, {z}");
Its not pretty, but it's better than adding the #[cfg(stuff)]
to every line
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With