I am trying to push an object which implements a trait with a trait parameter into a Vec
:
trait IRequest {}
trait IRequestHandler<T>
where
T: IRequest,
{
fn handle(&self, request: T);
}
pub struct CreateTodoRequest();
impl IRequest for CreateTodoRequest {}
pub struct CreateTodoRequestHandler();
impl IRequestHandler<CreateTodoRequest> for CreateTodoRequestHandler {
fn handle(&self, request: CreateTodoRequest) {}
}
fn main() {
let request = CreateTodoRequest {};
let handler = CreateTodoRequestHandler();
let mut handlers: Vec<&dyn IRequestHandler<dyn IRequest>> = Vec::new();
handlers.push(&handler);
}
I get an error:
error[E0277]: the trait bound `CreateTodoRequestHandler: IRequestHandler<dyn IRequest>` is not satisfied
--> src/main.rs:25:19
|
25 | handlers.push(&handler);
| ^^^^^^^^ the trait `IRequestHandler<dyn IRequest>` is not implemented for `CreateTodoRequestHandler`
|
= help: the following implementations were found:
<CreateTodoRequestHandler as IRequestHandler<CreateTodoRequest>>
= note: required for the cast to the object type `dyn IRequestHandler<dyn IRequest>`
When I had IRequestHandler
without a parameter, I could cast it and push into the Vec
. The problem only appears when the trait has a parameter.
Is it possible to cast an object to a trait with a parameter that it implements?