Skip to content

Commit 11dedff

Browse files
committed
cfg_select! macro
1 parent 93f3388 commit 11dedff

File tree

1 file changed

+37
-2
lines changed

1 file changed

+37
-2
lines changed

src/conditional-compilation.md

Lines changed: 37 additions & 2 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,11 +466,45 @@ 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+
# #![feature(cfg_select)
478+
cfg_select! {
479+
unix => {
480+
fn foo() { /* unix specific functionality */ }
481+
}
482+
target_pointer_width = "32" => {
483+
fn foo() { /* non-unix, 32-bit functionality */ }
484+
}
485+
_ => {
486+
fn foo() { /* fallback implementation */ }
487+
}
488+
}
489+
```
490+
The `cfg_select` macro can also be used in expression position:
491+
492+
```rust
493+
# #![feature(cfg_select)
494+
let is_unix_str = cfg_select! {
495+
unix => "unix",
496+
_ => "not unix",
497+
};
498+
```
499+
500+
A `_` can be used to write a configuration predicate that always evaluates to `true`.
501+
469502
[Testing]: attributes/testing.md
470503
[`--cfg`]: ../rustc/command-line-arguments.html#--cfg-configure-the-compilation-environment
471504
[`--test`]: ../rustc/command-line-arguments.html#--test-build-a-test-harness
472505
[`cfg`]: #the-cfg-attribute
473-
[`cfg` macro]: #the-cfg-macro
506+
[`cfg!`]: #the-cfg-macro
507+
[`cfg_select!`]: #the-cfg_select-macro
474508
[`cfg_attr`]: #the-cfg_attr-attribute
475509
[`crate_name`]: crates-and-source-files.md#the-crate_name-attribute
476510
[`crate_type`]: linkage.md
@@ -479,4 +513,5 @@ println!("I'm running on a {} machine!", machine_kind);
479513
[attributes]: attributes.md
480514
[cargo-feature]: ../cargo/reference/features.html
481515
[crate type]: linkage.md
516+
[macros]: macros.md
482517
[static C runtime]: linkage.md#static-and-dynamic-c-runtimes

0 commit comments

Comments
 (0)