Error about trait not satisfying itself in default implementation

Hello,

I'm trying to delegate functionality in a default implementation to a helper method, so I'm trying to have code like this:

fn fe(p: Box<dyn P>) {}

trait P {
    fn fp(&self) {
        fe(Box::new(self))
    }
}

The compiler says:

error[E0277]: the trait bound `&Self: P` is not satisfied
 --> src/experiment.rs:7:12
  |
7 |         fe(Box::new(self))
  |            ^^^^^^^^^^^^^^ the trait `P` is not implemented for `&Self`
  |
  = note: required for the cast to the object type `dyn P`

How can I fix this error? Thanks!

Best, Oliver

Do you need to Box it? Boxing comes with some additional requirements -- Sized and 'static. Another way to write your code could be this:

fn fe(p: &dyn P) {}

trait P {
    fn fp(&self) where Self: Sized {
        fe(self)
    }
}

The problem in the original code is that a reference to something that implements P doesn't necessarily itself implement P.

2 Likes

Thanks, that works! I thought I need Box, but looks like I don't.

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.