Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use feature flag in Rust to capture multiple lines of code?

Tags:

rust

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)?

like image 737
terett Avatar asked Sep 05 '25 01:09

terett


1 Answers

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

like image 110
cameron1024 Avatar answered Sep 07 '25 17:09

cameron1024