The following code results in an error (Playground)
#![feature(specialization)]
trait Foo {
type Assoc;
fn foo(&self) -> &Self::Assoc;
}
The Specialization
feature is showing no signs of stabilising, mostly because of soundness concerns, so you should expect some problems.
You have this:
#![feature(specialization)]
trait Foo {
type Assoc;
fn foo(&self) -> &Self::Assoc;
}
default impl<T> Foo for T {
type Assoc = T;
fn foo(&self) -> &Self::Assoc {
self
}
}
But imagine that you added another implementation with its own associated type but without implementing foo
. This implementation's foo
will be "inherited" from the other, less specific, implementation:
impl<T: SomeConstraint> Foo for T {
type Assoc = NotT;
}
Then there'd be a problem. Your foo
would be returning a T
but, whenever T is SomeConstraint
there'd be a type mismatch because it should be returning a NotT
.
RFC 2532 — associated type defaults mentions a possible solution in its Future Work section. A hypothetical default
block could be used to indicate that associated type(s) and method(s) would need to be specialized together. There's no sign of when such a feature would be considered for inclusion, however.