type_alias_impl_trait
The tracking issue for this feature is: #63063
This feature is not to be confused with
trait_alias
orimpl_trait_in_assoc_type
.
What is impl Trait
?
impl Trait
in return position is useful for declaring types that are constrained by traits, but whose concrete type should be hidden:
use std::fmt::Debug;
fn new() -> impl Debug {
42
}
fn main() {
let thing = new();
// What actually is a `thing`?
// No idea but we know it implements `Debug`, so we can debug print it
println!("{thing:?}");
}
See the reference for more information about impl Trait
in return position.
type_alias_impl_trait
However, we might want to use an impl Trait
in multiple locations but actually use the same concrete type everywhere while keeping it hidden.
This can be useful in libraries where you want to hide implementation details.
The #[define_opaque]
attribute must be used to explicitly list opaque items constrained by the item it's on.
In this example, the concrete type referred to by Alias
is guaranteed to be the same wherever Alias
occurs.
Originally this feature included type aliases as an associated type of a trait. In #110237 this was split off to
impl_trait_in_assoc_type
.
type_alias_impl_trait
in argument position.
Note that using Alias
as an argument type is not the same as argument-position impl Trait
, as Alias
refers to a unique type, whereas the concrete type for argument-position impl Trait
is chosen by the caller.
Note that the user cannot use #[define_opaque(Alias)]
to reify the opaque type because only the crate where the type alias is declared may do so. But if this happened in the same crate and the opaque type was reified, they'd get a familiar error: "expected MyType
, got UserType
".