|
| 1 | +# Why the standard library uses extension traits (and not `cfg`-guarded items) |
| 2 | + |
| 3 | +A common pattern in the standard library is to put target-specific methods into |
| 4 | +extension traits, rather than providing them as `cfg`-guarded methods directly |
| 5 | +on objects themselves. For example, the many extension traits in |
| 6 | +[`std::os::unix::prelude`](https://doc.rust-lang.org/std/os/unix/prelude/index.html) |
| 7 | +provide UNIX-specific methods on standard types. |
| 8 | + |
| 9 | +The standard library could, instead, provide these methods directly on the |
| 10 | +standard types, guarded by `#[cfg(unix)]`. However, it does not do so, and PRs |
| 11 | +adding `cfg`-guarded methods are often rejected. |
| 12 | + |
| 13 | +Providing these methods via extension traits forces code to explicitly use |
| 14 | +those extension traits in order to access the methods. This, effectively, |
| 15 | +requires code to declare whether it depends on target-specific functionality, |
| 16 | +either because the code is target-specific, or because it has appropriately |
| 17 | +`cfg`-guarded code for different targets. Without these extension traits, code |
| 18 | +could more easily use target-specific functionality "accidentally". |
| 19 | + |
| 20 | +This policy may change in the future if Rust develops better mechanisms for |
| 21 | +helping code explicitly declare its portability, or lack of portability, before |
| 22 | +accessing target-specific functionality. |
0 commit comments