是否可以有条件地编译函数内的代码块? [英] Is it possible to conditionally compile a code block inside a function?
问题描述
我想知道这样的事情是否可能
I'm wondering if something like this is possible
fn main() {
#[cfg(foo)] {
println!("using foo config");
}
}
上下文是一些无法仅通过单元测试进行充分测试的代码.我经常需要运行一个演示"cfg 来显示信息.我正在寻找替代手动注释输入/注释部分代码的方法.
The context is some code that cannot adequately be tested with just unit tests. I'll often have to run a "demo" cfg which displays information. I'm looking for alternatives to manually commenting in/out some portions of code.
推荐答案
至少从 Rust 1.21.1 开始,可以完全按照您所说的来执行此操作:
As of at least Rust 1.21.1, it's possible to do this as exactly as you said:
fn main() {
#[cfg(foo)]
{
println!("using foo config");
}
}
<小时>
在此之前,不可能完全有条件地做到这一点(即避免块完全被类型检查),这样做由 RFC #16.但是,您可以使用 cfg
宏,它根据 --cfg
标志评估为 true
或 false
:
Before this, it isn't possible to do this completely conditionally (i.e. avoiding the block being type checked entirely), doing that is covered by RFC #16. However, you can use the cfg
macro which evaluates to either true
or false
based on the --cfg
flags:
fn main() {
if cfg!(foo) { // either `if true { ... }` or `if false { ... }`
println!("using foo config");
}
}
if
的主体总是运行名称解析和类型检查,因此可能并不总是有效.
The body of the if
always has name-resolution and type checking run, so may not always work.
这篇关于是否可以有条件地编译函数内的代码块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!