Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading