Subtypes and trait objects


I want to write code like

struct MyError  {
    inner: Box<dyn Error + Send + Sync + 'static>,

impl Error for MyError {
    fn source(&self) -> &(dyn Error + 'static) {

but rust doesn’t seem to figure out that Error + Send + Sync + 'static must also be Error + 'static. Am I missing something?

EDIT My example isn’t correct. It should be

impl Error for MyError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        self.inner.as_ref().map(|e| &**e as &(dyn StdError + 'static))

(note the as cast I need to make it work). Can I avoid the cast and still get it to compile?


Hi, you just forgot to dereference the Box


the compiler thinks you’re trying to return a &Box<dyn Error>.

1 Like

I would like to provide an example, but it seems I’ve broken the playground :cold_sweat:


That’s not you, the playground can’t compile anything on nightly right now.

1 Like