Is it possible to conditionally compile a code block inside a function?

前端 未结 2 1896
日久生厌
日久生厌 2021-01-21 01:36

I\'m wondering if something like this is possible

fn main() {
    #[cfg(foo)] {
        println!(\"using foo config\");
    }

}

The context is

2条回答
  •  梦毁少年i
    2021-01-21 01:57

    You may interested in the crate cfg-if, or a simple macro will do:

    macro_rules! conditional_compile {
        ($(#[$ATTR:meta])* { $CODE: tt }) => {
            {
                match 0 {
                    $(#[$ATTR])*
                    0 => $CODE,
    
                    // suppress clippy warnning `single_match`.
                    1 => (),
                    _ => (),
                }
            }
        }
    }
    
    fn main() {
        conditional_compile{
            #[cfg(foo)]
            {{
                println!("using foo config");
                // Or something only exists in cfg foo, like a featured mod.
            }}
        }
    }
    

提交回复
热议问题