Summary
This RFC proposes a mechanism for crates to define default bounds on generics. By specifying these defaults at the crate level we can reduce the need for verbose and repetitive ?Trait annotations while maintaining backward compatibility and enabling future language evolution.
Motivation
What are ?Trait bounds
Generic parameters on functions (fn foo<T>()), associated types in traits trait Foo { type Assoc; } and Self in traits trait Foo where Self ... can have where bounds.
This function expects any T that can be compared via == operator:
But Rust introduces some bounds by default. In the code above, T must be both PartialEq and Sized. To opt out of this, users need to write + ?Sized manually:
Sized>
Use of ?Trait bounds for new features
A lot of new features (see #use-cases) require breaking old code by removing long-established assumptions like size = stride or the ability to skip the destructor of a type. To avoid breaking the code, they create a new trait representing an assumption and then define their feature as types that do not implement this trait. Here ?Trait bounds come in - old code has old assumptions, but new code can add ?Trait to opt out of them and support more types.
It is also important to note that in most cases those assumptions are not actually exercised by generic code, they are just already present in signatures - rarely code needs size = stride, or to skip the destructor (especially for a foreign type).
The problem
Quotes from "Size != Stride" Pre-RFC thread:
In order to be backwards compatible, this change requires a new implicit trait bound, applied everywhere. However, that makes this change substantially less useful. If that became the way things worked forever, then
#[repr(compact)]types would be very difficult to use, as almost no generic functions would accept them. Very few functions actually needAlignSized, but every generic function would get it implicitly.
@scottmcm
Note that every time this has come up --
?Move,?Pinned, etc -- the answer has been "we're not adding more of these".What would an alternative look like that doesn't have the implicit trait bound?
In general, many abstractions can work with both Trait and !Trait types, and only a few actually require Trait. For example, Forget bound is necessary for only a few functions in std, such as forget and Box::leak, while Option can work with !Forget types too.
However, if Rust were to introduce ?Forget, every generic parameter in std would need an explicit ?Forget bound. This would create excessive verbosity and does not scale well.
There is a more fundamental problem noted by @bjorn3: std would still need to have Forget bounds on all associated items of traits to maintain backward compatibility, as some code may depend on them. This makes !Forget types significantly harder to use and reduces their practicality. Fortunately, @Nadrieril proposed a solution to that problem, which resulted in that RFC.
See #guide-level-explanation for details.
Use cases
!Forgettypes - types with a guarantee that destructors will run at the end of their lifetime. Those types are crucial for async and other language features, which are described inforget_marker_traitPre-RFC.Size != Strideis a frequently requested feature, but it is fundamentally backward-incompatible change that requires?AlignSizedbound.Must movetypes will benefit from this too, further improving async ergonomics.
The expected outcome is an open road for new language features to enter the language in a backward-compatible way and allow users and libraries to adapt gradually.
Guide-level explanation
This RFC is targeted at supporting migrations from default being Trait to ?Trait, where Trait represents some assumption that is present everywhere but is not really exercised a lot, such as Forget, size = stride etc. Features like DynSized, as well as extern types, are out of the scope of this RFC, because it does not fit into this category. DynSized is not retracting mostly unexercised assumptions in order to make it ?DynSized the default.
The syntax is to be bikeshedded, initially, it might be with a crate-level attributes.
The following example demonstrates how the compiler will understand the code. PartialEq is used just for illustration purposes. In reality, only a special set of traits would be allowed and would grow with new "breaking" traits, like Forget. PartialEq would not be one of them.
use Deref;
;
;
;
;
PartialEq>
Code above will be observable as (code in today's Rust without any defaults):
use Deref;
;
;
;
;
Forget + PartialEq>
Forget>
Introducing this feature is backward compatible and does not require an edition.
RFC tries to be consistent with already existing handling of Sized.
Example: Migrating to Forget
With this RFC, transitioning to Forget is straightforward for any #![forbid(unsafe)] crate:
- Set the appropriate bounds:
-
Resolve any compilation errors by explicitly adding
+ Forgetwhere needed. -
Optionally: Recurse into your dependencies, applying the same changes as needed.
Crates using unsafe code should beware of ptr::write and other unsafe ways of skipping destructors.
Implications on the libraries
Relax generic bound on public API
For migrated users it is equivalent to semver's minor change, while not migrated uses will observe it as patch change.
Weakening associated type bound and Self bound in traits
Traits and associated types will ignore default_generic_bounds and always default to the most permissive possible bounds:
This change would not be observable for not migrated crates, because default_generic_bounds would default to Trait, which takes effect on function generic arguments. But if users start migrate before libraries, they will not lock them into old bounds.
async
// Libary that has not migrated yet.
Macros
If macro-library generates code, some problems during the migration are possible:
Reference-level explanation
Introduce new crate level attibute: default_generic_bounds used to (non-exhaustively) enumerate overwrides of defaults for different types of bounds. Only a special set of traits would be allowed and would grow with new "breaking" traits, like Forget.
Every trait would initally have its unique default. In practice, bounds for all traits that are stable at the date of RFC except Sized would default to ?Trait. For new "breaking" traits, default would be Trait, except bounds for Self in traits and associated types in traits.
https://rust-lang.github.io/rfcs/0546-Self-not-sized-by-default.html
default_generic_bounds is applied for generic parameters. Effectively, it would be observable like that:
// crate `b` that has not migrated to `#![default_generic_bounds(?Forget)]`
Drawbacks
- It may increase compilation time due to the additional complexity of trait solving.
- It may make reading source files of crates harder, as the reader should first look at the top of the crate to see the defaults, and then remember them. It may increase cognitive load.
- It may take some time for the ecosystem around the language to fully adapt
!Trait, but it will not include semver breaking changes for libraries or Rust code in general. Similar toconst fnnow.
Rationale and alternatives
This design is simple yet powerful because it offers a backward-compatible way to evolve the language.
The impact of not accepting this RFC is that language features requiring types like !Forget, MustMove,
!AlignSized and many others will not be accepted.
Default Auto Traits
This is a very similar proposal which is partially implemted already, could totally be an alternative path. It makes same trick over an edition for traits that we want to remove from defaults. In the case of Forget, we may set default bound for crates of edition 2024 and earlier, and lift it for editions after 2024. In terms of this RFC, it would mean that editions would have different presets of default bounds, while users would not be able to manipulate them manually.
Pros of this is that we do not need a new syntax and implementation should be simpler.
Cons are that migration is more invasive and enormous, and feels more "forced" - to migrate to the new edition, you must migate to the new bound (or several bounds). The other thing is that Default Auto Traits makes no mention of what would happen (but it probably can be added) if library did not migrate to the next edition but users did - would library be locked into Trait bounds in associated types (like async functions) and need a breaking semver change to remove it? local_default_bounds address that issue directly and allows for non-breaking changes.
Add fine-grained attributes
We may have four attributes: default_generic_bounds, default_foreign_assoc_bounds, default_trait_bounds and default_assoc_bounds for more fine-grained control over defaults. For example, Sized has following defaults:
Previous version of this RFC was exactly this, you can read it here.
Alternative syntax
We may have a single macro to declare all bounds:
declare_default_bounds! ;
Do not default Self in traits and associated types to ?Trait from the beginning
This will drastically reduce implementation complexity as it would be possible to do with a simple desugaring, because recursive bounds would not need to be infinitely bounded. But it will open a possibility for libraries to be locked into Forget bounds in some cases.
Prior art
Links
- Default auto traits: https://github.com/rust-lang/rust/pull/120706
SelfnotSizedby default: https://rust-lang.github.io/rfcs/0546-Self-not-sized-by-default.html
Unresolved questions
- [ ] How to handle GATs? Rustc currently does not support proving
for<U> <T as Trait>::Assoc<U>: Forget. - [ ] How to solve recursive associated type bounds?
trait Trait { type Assoc: Trait } - [ ] We probably don't want to alter macro output, it would probably be too hard to implement and design. How should we handle this?
// macro crate
// user crate
make_functions!
- [ ] Syntax
- [ ] How to display it in Rustdoc
- [ ] Should we allow default
!bounds? What would it mean? - [ ] Maybe use the term "implicit" instead of "default".
- [ ] Should we allow
Sized. - [ ] Maybe have 4 different attributes for more fine-grained control?
- [ ] Maybe go with Default auto traits.
Shiny future we are working towards
Less backward compatibility burden and more freedom to fix old mistakes, to propose new features.