How many lines are covered by the Rust conditional compilation attribute?

牧云@^-^@ 提交于 2020-02-24 09:14:05

问题


I'm trying to use a conditional compilation statement. Beyond defining a function that should only exist in a debug build, I want to define a set of variables/constants/types that only exist in the debug build.

#[cfg(debug)]
pub type A = B;
pub type B = W;

#[cfg(other_option)]
pub type A = Z;
pub type B = I;
let test = 23i32;

How many lines are actually "covered" by the conditional compile attribute in this case? Is it only one (what I would expect in this context)? Are there ways to ensure that a whole block of code (including variables, types and two functions) is covered by the condition?


回答1:


An #[attribute] only applies to the next item. Please see the Rust book.

Edit: I don't think it is currently possible to spread an attribute over an arbitrary number of declarations.

Additional, in-depth information on attributes and their application can be found at Rust reference.




回答2:


You can use a module to group together everything that should exist for debug/release only, like this:

#[cfg(debug)]
mod example {
    pub type A = i32;
    pub type B = i64;
}

#[cfg(not(debug))]
mod example {
    pub type A = u32;
    pub type B = u64;
}

fn main() {
    let x: example::A = example::A::max_value();
    println!("{}", x);
}

Playground link (note that this will always print the not(debug) value because the playground doesn't define the debug feature, even in debug mode).

If debug is defined, this will print 2147483647 (the maximum value of an i32), otherwise it will print 4294967295 (the maximum value of a u32). Keep in mind that both modules must have definitions for each item, otherwise you'll hit a compile-time error.

If you've not read about Attributes, it might be a good idea to do so; make sure you know the difference between inner attributes (#![attribute]) and outer attributes (#[attribute]).



来源:https://stackoverflow.com/questions/39291850/how-many-lines-are-covered-by-the-rust-conditional-compilation-attribute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!