I am trying to implement function get_render_module
that should return a specific type while the container (HashMap
) contains a trait objects. How can i cast one to another without any "unsafe" code?
This is the sample code:
pub type ModuleRef = Arc<RefCell<dyn Module>>;
#[derive(Debug)]
pub struct RenderModule {}
impl Display for RenderModule {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
todo!()
}
}
impl Module for RenderModule {
fn reload(&mut self) -> Result<(), ModuleInternalError> {
Ok(())
}
fn name(&self) -> &str {
"render"
}
fn call_capability(
&mut self,
cap_name: &str,
arguments: Vec<TransferType>,
) -> Result<TransferType, CapabilityCallError> {
todo!()
}
}
pub trait Module: fmt::Display + Debug {
fn reload(&mut self) -> Result<(), ModuleInternalError>;
fn name(&self) -> &str;
fn call_capability(
&mut self,
cap_name: &str,
arguments: Vec<TransferType>,
) -> Result<TransferType, CapabilityCallError>;
}
#[derive(Debug, Clone, PartialEq)]
pub enum CapabilityCallError {
ModuleNameInvalid,
}
#[non_exhaustive]
#[derive(Debug, Default)]
pub struct Server {
modules: HashMap<String, ModuleRef>,
}
impl Server {
pub fn find_module(&self, name: &str) -> Result<ModuleRef, CapabilityCallError> {
self.modules.get(name).cloned().ok_or(CapabilityCallError::ModuleNameInvalid)
}
}
pub fn get_render_module(server: &Server) -> &RenderModule {
todo!()
}