Description
This issue tracks the release notes text for #134367.
Steps
- Proposed text is drafted by PR author (or team) making the noteworthy change.
- Issue is nominated for release team review of clarity for wider audience.
- Release team includes text in release notes/blog posts.
Release notes text
The responsible team for the underlying change should edit this section to replace the automatically generated link with a succinct description of what changed, drawing upon text proposed by the author (either in discussion or through direct editing).
# Language
- [Stabilize the ability to upcast a trait object to one of its supertraits.](https://github.com/rust-lang/rust/pull/134367)
Tip
Use the previous releases categories to help choose which one(s) to use.
The category will be de-duplicated with all the other ones by the release team.
More than one section can be included if needed.
Release blog section
If the change is notable enough for inclusion in the blog post, the responsible team should add content to this section.
Otherwise leave it empty.
# Trait upcasting
This release includes a long awaited feature — the ability to upcast trait objects.
If a trait has a [supertrait](https://doc.rust-lang.org/reference/items/traits.html#supertraits) you can coerce a reference to said trait object to a reference to a trait object of the super trait:
```rust
trait Trait: Supertrait {}
trait Supertrait {}
fn upcast(x: &dyn Trait) -> &dyn Supertrait {
x
}
```
The same would work with any other kind of (smart)-pointer, like `Arc<dyn Trait> -> Arc<dyn Supertrait>` or `*const dyn Trait -> *const dyn Supertrait`.
Previously this would require a workaround in the form of an `upcast` method in the `Trait` itself (and that would work only for one kind of reference/pointer). Such workarounds are not necessary anymore.
Note that this adds a new _safety invariant_ to raw pointers — if a pointer points to a trait object, vtable must be valid for that trait. This means that "leaking" a raw pointer to a trait object with an invalid vtable into safe code may lead to undefined behavior.
Trait upcasting may be especially useful with the `Any` trait, as it allows upcasting your trait object to `dyn Any` to call the downcast methods. Whereas before you'd have to write workarounds for this or use external crates.
```rust
use std::any::Any;
trait MyAny: Any {}
impl dyn MyAny {
fn downcast_ref<T>(&self) -> Option<&T> {
(self as &dyn Any).downcast_ref()
}
}
```
You can [learn more about trait upcasting in the Rust reference](https://doc.rust-lang.org/reference/type-coercions.html#unsized-coercions).
cc @WaffleLapkin, @compiler-errors -- origin issue/PR authors and assignees for starting to draft text