Compilation error: Associated types and Trait Object

Let's define associated type for any abstract handlers:

trait Handler {
    type Error;
    fn handle(&mut self) -> Result<(), Self::Error>;
}

and try to implement it, but errors has many variant, so i use trait object for this:

use std::error::Error;
type AnyError = Box<dyn Error + Send + Sync + 'static>;

struct MyHandler;
impl Handler for MyHandler {
    type Error = AnyError;
    fn handle(&mut self) -> Result<(), AnyError> {
        Ok(())
    }
} 

It's compilation is ok, all together at playground

Now, i need to print error and so i change trait:

trait Handler {
    type Error: Debug;
    fn handle(&mut self) -> Result<(), Self::Error>;
}

It's also compilation is ok, all together at playground

but if i more specify type Error, i got compilation error:

trait Handler {
    type Error: Error;
    fn handle(&mut self) -> Result<(), Self::Error>;
}
the size for values of type `(dyn std::error::Error + Send + Sync + 'static)` cannot be known at compilation time

playground

But i do not understand why?

This is because Box<dyn Error + Send + Sync> doesn't actually implement error. The error talks about Sized because the impl of Error for Box<T> requires T to be sized.

3 Likes