Impl Error for Box<dyn Error>?

I've recently discovered that Box<dyn Error> apparently does not implement the Error trait.

This issue has appeared before on this board, but I'm still confused by two things. I understand that the Sized requirement comes from the implementation

impl<T: Error> Error for Box<T> { ... }

which has an implicit Sized bound on the type parameter T. What confuses me is...

  1. Why does the error message underline a value of type Box<dyn Error> and claim it is unsized? Aren't boxes always sized?
  2. Why is this impl not written to work for T: ?Sized?

The answer to the second seems to be "because it conflicts with a From impl", but I seem to be able to write my own trait that does this just fine. So what gives?

The stdlib has its own impls, including two below.

impl<T> From<T> for T {...}

impl<E: Error> From<T> for Box<dyn Error> {...}

And they will be conflict on From<Box<dyn Error>> impl of Box<dyn Error> type if we add impl From<Box<dyn Error>> for Box<dyn Error>

Ah, I missed the second impl. That makes sense, thank you!

Worth noting that when specialization is stabilized, this would be allowed (I think?)

Yes, it will be allowed because impl<E: Error> From<T> is more specific than impl<T> From<T>. We can probably have this now because the standard library is allowed to use unstable features like specialisation on stable... Whether we want to actually add it is another thing. Trait implementations also can't be made nightly-only, so adding the impl will be insta-stable.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.