So I've never really worked with type erasure, but the term seems fitting for what I did right here. The whole purpose of this is to allow my to use a dyn TypeErasedCommandHandler.
Is this code considered alright? Is there a better way to do this?
Is this even considered "type erasure" or am I confusing this term here?
pub trait TakeableCommandHandler: Sync + Send {
type Dispatcher: CommandDispatcher;
fn key(&self) -> &'static str {
Self::Dispatcher::key()
}
fn handle(&self, session: &mut Option<Session>) -> impl Future<Output = Result<()>> + Send;
}
#[async_trait]
pub trait TypeErasedCommandHandler: Send + Sync {
fn key(&self) -> &'static str;
async fn handle(&self, session: &mut Option<Session>) -> Result<()>;
}
#[async_trait]
impl<T> TypeErasedCommandHandler for T
where
T: TakeableCommandHandler,
{
fn key(&self) -> &'static str {
self.key()
}
async fn handle(&self, session: &mut Option<Session>) -> Result<()> {
self.handle(session).await
}
}
pub struct HandlerCollection {
commands: Arc<RwLock<HashMap<String, Arc<dyn TypeErasedCommandHandler>>>>,
}