0

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?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
  • See also [How can I have a collection of objects that differ by their associated type?](https://stackoverflow.com/q/28932450/155423) – Shepmaster Sep 01 '20 at 16:53
  • The [most direct fix applied to your code](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=fbd5f91601652eceaea7f527db213348). – Shepmaster Sep 01 '20 at 16:54
  • @Shepmaster Thank you for the feedback and for corrected my question. I readed all attached links and if I understood them correctly there isn't any easy way to push into Vec many different objects (handlers) which implements IRequestHandler beacause this trait with parameter isn't object-safe – pager_dev Sep 02 '20 at 08:46

0 Answers0