Skip to content

Explain why the standard library uses extension traits rather than cfg #71

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jan 10, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/SUMMARY.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
- [Doc alias policy](./policy/doc-alias.md)
- [Safety comments policy](./policy/safety-comments.md)
- [Reviewing target-specific code](./policy/target-code.md)
- [Why the standard library uses extension traits](./policy/extension-traits.md)

- [Tricky situations]()
- [Drop and `#[may_dangle]`](./tricky/may-dangle.md)
Expand Down
22 changes: 22 additions & 0 deletions src/policy/extension-traits.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# Why the standard library uses extension traits (and not `cfg`-guarded items)

A common pattern in the standard library is to put target-specific methods into
extension traits, rather than providing them as `cfg`-guarded methods directly
on objects themselves. For example, the many extension traits in
[`std::os::unix::prelude`](https://doc.rust-lang.org/std/os/unix/prelude/index.html)
provide UNIX-specific methods on standard types.

The standard library could, instead, provide these methods directly on the
standard types, guarded by `#[cfg(unix)]`. However, it does not do so, and PRs
adding `cfg`-guarded methods are often rejected.

Providing these methods via extension traits forces code to explicitly use
those extension traits in order to access the methods. This, effectively,
requires code to declare whether it depends on target-specific functionality,
either because the code is target-specific, or because it has appropriately
`cfg`-guarded code for different targets. Without these extension traits, code
could more easily use target-specific functionality "accidentally".

This policy may change in the future if Rust develops better mechanisms for
helping code explicitly declare its portability, or lack of portability, before
accessing target-specific functionality.