如何在 Rust 中使用 cfg 检查发布/调试版本?

How to check release / debug builds using cfg in Rust?

对于 C 预处理器,这是很常见的,

#if defined(NDEBUG)
    // release build
#endif

#if defined(DEBUG)
    // debug build
#endif

Cargo 的粗略等价物是:

如何使用 Rust 的 #[cfg(...)] 属性或 cfg!(...) 宏来做类似的事情?

我知道 Rust 的预处理器不像 C 那样工作。我检查了文档和 this page lists some attributes(假设此列表是全面的)

debug_assertions 可以检查,但在用于检查更一般的调试情况时可能会产生误导。

我不确定这个问题是否与 Cargo 有关。

您可以使用debug_assertions as the appropriate configuration flag. It works with both #[cfg(...)] attributes and the cfg!宏:

#[cfg(debug_assertions)]
fn example() {
    println!("Debugging enabled");
}

#[cfg(not(debug_assertions))]
fn example() {
    println!("Debugging disabled");
}

fn main() {
    if cfg!(debug_assertions) {
        println!("Debugging enabled");
    } else {
        println!("Debugging disabled");
    }

    #[cfg(debug_assertions)]
    println!("Debugging enabled");

    #[cfg(not(debug_assertions))]
    println!("Debugging disabled");

    example();
}

此配置标志在 this discussion 中被命名为执行此操作的正确方法。暂时没有更合适的内置条件

来自reference:

debug_assertions - Enabled by default when compiling without optimizations. This can be used to enable extra debugging code in development but not in production. For example, it controls the behavior of the standard library's debug_assert! macro.

另一种稍微复杂的方法是使用 #[cfg(feature = "debug")] 并创建一个构建脚本,为您的 crate 启用“调试”功能,如图 here.