4 ms·
> Finally, it’s possible to implement a trait for all classes that implement one of a number of other traits, but it requires specialization, which is a nightly
by ibraheemdev 5y ago
> Finally, it’s possible to implement a trait for all classes that implement one of a number of other traits, but it requires specialization, which is a nightly feature for now (though there is a workaround available, even packed in a macro crate if you don’t want to write out all the boilerplate required).
This is false. You can easily write a blanket impl in stable Rust:
impl<T> Foo for T where T: Bar + Baz {
fn foo(&self) {
self.bar().baz()
}
}
Specialization allows you to create multiple impls, depending on what traits a generic type implements. This is a very powerful feature that is available on nightly, but it is also easy to misuse and create unwanted implicit behavior.
impl<T> Foo for T {
default fn foo(&self) {
// do nothing by default
}
}
impl<T> Foo for T where T: Bar + Baz {
fn foo(&self) {
self.bar().baz()
}
}
- Diggsey 5y agoThe author is referring to the case where you have multiple traits, and want to provide implentations like: impl<T: Cat> Animal for T { ... } impl<T: Dog> Animal for T { ... } This is impossible without specialization, since there's no way to express the constraint that no type implements both `Dog` and `Cat`. Having multiple blanket trait implementations like this can be used to emulated inheritance, whereas a single blanket implementation cannot.