01-自定义条件

自定义条件 — Rust By Example

译文 · 基于 Rust By Example

原文链接: https://doc.rust-lang.org/stable/rust-by-example/attribute/cfg/custom.html

自定义条件

有部分条件如 target_os 是由 rustc 隐式地提供的,但是自定义条件必须使用 --cfg 标记来传给 rustc。

1
2
3
4
5
6
7
8
#[cfg(some_condition)]
fn conditional_function() {
    println!("condition met!")
}

fn main() {
    conditional_function();
}

试试不使用自定义的 cfg 标记会发生什么:

1
2
$ rustc custom.rs && ./custom
No such file or directory (os error 2)

使用自定义的 cfg 标记:

1
2
$ rustc --cfg some_condition custom.rs && ./custom
condition met!
最后修改 August 21, 2026: 更新 (76fc81a2e)