Description
There are a few common mistakes people make involving trait objects, where instead of getting a helpful error, they end up getting some error about how their trait doesn't implement Sized
. This can be extremely confusing, and it doesn't given any guidance to help the user solve their actual issue.
It would be great if we could just get special case error messages for each of these situations that tell the user how their problem can be solved.
Here are a few common cases I see often:
The trait is not in scope
A common pattern (shared by Iterator
and Future
for example) is to have parametric provided methods bounded by Self: Sized
& an implementation of Trait for Box<T> where T: Trait + ?Sized
.
If you end up getting a Box<Trait>
in a scope where you don't have the trait in scope, method resolution will deref your box, and try to call the method on the raw, dynamically sized trait object, which will result in an error about how 'Trait + 'static: Sized' not satisfied
.
A minimal example:
trait Foo {
fn bar(&self) where Self: Sized { }
}
impl<F: Foo + ?Sized> Foo for Box<F> { }
impl Foo for () { }
fn foo() -> Box<Foo> { Box::new(()) }
mod bar {
use foo;
fn bar() {
foo().bar();
}
}
The actual solution to this is to import the trait into the scope in question, so that the Box's impl will be delegated to, instead of the raw object.
One wonders if there isn't a deeper solution to this problem, but at minimum we could recognize cases where you could instead delegate to the Box impl and suggest importing the trait instead.
You didn't mean to implement it for the trait object
Users who haven't fully internalized the idea of "parametric polymorphism" will often come upon the idea of providing a blanket impl, and write it like this:
trait Foo { }
trait Bar: Sized { }
impl Foo for Bar { }
Often, Bar
is not object safe, and so you get a Sized
issue. Sometimes, Bar
is object safe, and so you get an even more confusing error when you try to invoke a Foo method on a Bar type.
Implementing a trait for an unsized trait object is almost never what you want to do to (I've never wanted to, at least). At very least, in the case where the trait is not object-safe, we could suggest that what you actually want is this:
impl<T> Foo for T where T: Bar { }