fn cast_or_return(initial_obj: Box<dyn MyTrait>) -> Result<Box<Obj>, Box<dyn MyTrait>> {
if (&*initial_obj as &dyn Any).downcast_ref::<Obj>().is_some() {
(initial_obj as Box<dyn Any>)
.downcast::<Obj>()
.map_err(|_| unreachable!())
} else {
Err(initial_obj)
}
}
it's ugly, it does the chack twice (that will be optimized away in release mode), it has a very sus unreachable!, but it works and i don't think there is anything better
if (&*initial_obj as &dyn Any).type_id() == TypeId::of::<Obj>() {
let ptr = Box::into_raw(initial_obj) as *mut Obj;
// SAFETY: We just confirmed the `TypeId`
unsafe {
Ok(Box::from_raw(ptr))
}
} else {
Err(initial_obj)
}