Skip to content

Commit a93da68

Browse files
committed
cfg_select! macro
1 parent 93f3388 commit a93da68

File tree

1 file changed

+37
-3
lines changed

1 file changed

+37
-3
lines changed

src/conditional-compilation.md

Lines changed: 37 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ r[cfg.general]
3131
*Conditionally compiled source code* is source code that is compiled only under certain conditions.
3232

3333
r[cfg.attributes-macro]
34-
Source code can be made conditionally compiled using the [`cfg`] and [`cfg_attr`] [attributes] and the built-in [`cfg` macro].
34+
Source code can be made conditionally compiled using the [`cfg`] and [`cfg_attr`] [attributes] and the built-in [`cfg!`] and [`cfg_select!`] [macros].
3535

3636
r[cfg.conditional]
3737
Whether to compile can depend on the target architecture of the compiled crate, arbitrary values passed to the compiler, and other things further described below.
@@ -466,17 +466,51 @@ let machine_kind = if cfg!(unix) {
466466
println!("I'm running on a {} machine!", machine_kind);
467467
```
468468
469+
r[cfg.cfg_select]
470+
### The `cfg_select` macro
471+
472+
The built-in `cfg_select` macro expands to the right-hand side of the first configuration predicate that evaluates to `true`.
473+
474+
For example:
475+
476+
```rust
477+
cfg_select! {
478+
unix => {
479+
fn foo() { /* unix specific functionality */ }
480+
}
481+
target_pointer_width = "32" => {
482+
fn foo() { /* non-unix, 32-bit functionality */ }
483+
}
484+
_ => {
485+
fn foo() { /* fallback implementation */ }
486+
}
487+
}
488+
```
489+
490+
The `cfg_select` macro can also be used in expression position:
491+
492+
```rust
493+
let is_unix_str = cfg_select! {
494+
unix => "unix",
495+
_ => "not unix",
496+
};
497+
```
498+
499+
A `_` can be used to write a configuration predicate that always evaluates to `true`.
500+
469501
[Testing]: attributes/testing.md
470502
[`--cfg`]: ../rustc/command-line-arguments.html#--cfg-configure-the-compilation-environment
471503
[`--test`]: ../rustc/command-line-arguments.html#--test-build-a-test-harness
472504
[`cfg`]: #the-cfg-attribute
473-
[`cfg` macro]: #the-cfg-macro
474-
[`cfg_attr`]: #the-cfg_attr-attribute
505+
[`cfg!`]: #the-cfg-macro
506+
[`cfg_select!`]: #the-cfg_select-macro
507+
[`cfg_attr!`]: #the-cfg_attr-attribute
475508
[`crate_name`]: crates-and-source-files.md#the-crate_name-attribute
476509
[`crate_type`]: linkage.md
477510
[`target_feature` attribute]: attributes/codegen.md#the-target_feature-attribute
478511
[attribute]: attributes.md
479512
[attributes]: attributes.md
480513
[cargo-feature]: ../cargo/reference/features.html
481514
[crate type]: linkage.md
515+
[macros]: macros.md
482516
[static C runtime]: linkage.md#static-and-dynamic-c-runtimes

0 commit comments

Comments
 (0)