Hi all, I'm trying to do the following:
- I have a few objects that implement a trait: Handler
- each Handler can Handle a Command
Now I want to link handler to command in such a way that I can invoke something like
associations.get(command.getName()).handle(command)
a Command is defined as follows
pub trait Command {
fn name() -> & 'static str;
}
an handler is defined as follows
pub trait Handler<T: Command> {
type Result;
fn handle(&mut self, msg: T) -> impl Future<Output = Self::Result> + Send;
}
Now, I want to implement Command1 that is executed for CommandHandler1 and Command2 that is executed for CommandHandler2. So far so good.
My problem is that I want a facility, I was thinking an hashmap, where the keys are the names of the command (str
) and the value is the actual instance of a CommandHandler, such that given a Command that I've built in a function, I could use this hashmap to invoke the corresponding CommandHandler. But I get a lot of troubles with the typing because if I try to implement such an hashmap with the type HashMap<&str, Handler>
the compiler complains because Handlers cannot be made into objects.
All I want to do here is really making sure that the value implements this trait so that I can just invoke the handle
function.
Is there a good way to achieve this in rust? I'm happy to change approach if there is a better way to achieve the same result