curoli
October 27, 2021, 3:36pm
1
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
ecton
October 27, 2021, 3:44pm
2
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)
}
}
alice
October 27, 2021, 3:48pm
3
The problem in the original code is that a reference to something that implements P
doesn't necessarily itself implement P
.
2 Likes
curoli
October 27, 2021, 3:59pm
4
Thanks, that works! I thought I need Box, but looks like I don't.
system
Closed
January 25, 2022, 3:59pm
5
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.