Rust 条件编译属性覆盖了多少行?
How many lines are covered by the Rust conditional compilation attribute?
我正在尝试使用条件编译语句。除了定义只应存在于调试版本中的函数外,我还想定义一组仅存在于调试版本中的 variables/constants/types。
#[cfg(debug)]
pub type A = B;
pub type B = W;
#[cfg(other_option)]
pub type A = Z;
pub type B = I;
let test = 23i32;
在这种情况下,条件编译属性实际上 "covered" 有多少行?它只有一个(我在这种情况下所期望的)吗?有没有办法确保整个代码块(包括变量、类型和两个函数)都被条件覆盖?
一个#[attribute]
只适用于下一个item. Please see the Rust book。
编辑:我认为目前不可能将一个属性分布在任意数量的声明中。
有关属性及其应用的其他深入信息,请访问 Rust reference。
您可以使用一个模块将仅 debug/release 应该存在的所有内容组合在一起,如下所示:
#[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(请注意,这将始终打印 not(debug)
值,因为 playground 没有定义 debug
功能,即使在调试模式下也是如此)。
如果定义了debug
,这会打印2147483647
(一个i32
的最大值),否则打印4294967295
(一个i32
的最大值u32
)。请记住,两个模块都必须对每个项目都有定义,否则你会遇到编译时错误。
如果您还没有读过 Attributes,读一读可能是个好主意;确保您知道内部属性 (#![attribute]
) 和外部属性 (#[attribute]
) 之间的区别。
我正在尝试使用条件编译语句。除了定义只应存在于调试版本中的函数外,我还想定义一组仅存在于调试版本中的 variables/constants/types。
#[cfg(debug)]
pub type A = B;
pub type B = W;
#[cfg(other_option)]
pub type A = Z;
pub type B = I;
let test = 23i32;
在这种情况下,条件编译属性实际上 "covered" 有多少行?它只有一个(我在这种情况下所期望的)吗?有没有办法确保整个代码块(包括变量、类型和两个函数)都被条件覆盖?
一个#[attribute]
只适用于下一个item. Please see the Rust book。
编辑:我认为目前不可能将一个属性分布在任意数量的声明中。
有关属性及其应用的其他深入信息,请访问 Rust reference。
您可以使用一个模块将仅 debug/release 应该存在的所有内容组合在一起,如下所示:
#[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(请注意,这将始终打印 not(debug)
值,因为 playground 没有定义 debug
功能,即使在调试模式下也是如此)。
如果定义了debug
,这会打印2147483647
(一个i32
的最大值),否则打印4294967295
(一个i32
的最大值u32
)。请记住,两个模块都必须对每个项目都有定义,否则你会遇到编译时错误。
如果您还没有读过 Attributes,读一读可能是个好主意;确保您知道内部属性 (#![attribute]
) 和外部属性 (#[attribute]
) 之间的区别。