Skip to content

Commit f4feb32

Browse files
authored
Merge pull request #71 from joshtriplett/extension-traits
Explain why the standard library uses extension traits rather than `cfg`
2 parents 34d39de + 5b1f527 commit f4feb32

File tree

2 files changed

+23
-0
lines changed

2 files changed

+23
-0
lines changed

src/SUMMARY.md

+1
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
- [Doc alias policy](./policy/doc-alias.md)
2222
- [Safety comments policy](./policy/safety-comments.md)
2323
- [Reviewing target-specific code](./policy/target-code.md)
24+
- [Why the standard library uses extension traits](./policy/extension-traits.md)
2425

2526
- [Tricky situations]()
2627
- [Drop and `#[may_dangle]`](./tricky/may-dangle.md)

src/policy/extension-traits.md

+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
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

Comments
 (0)