我想知道下面的代码是否有效(也许有一种内置/安全的方法将Rc<dyn SomeTrait>
转换为Rc<SomeType>
?我找不到),最重要的是,它安全吗?
use std::any::*;
use std::rc::*;
// NOTE: apparently adding Any here is REQUIRED
// otherwise it doesn't work at all,
// I have no idea why
trait SomeTrait: Any {}
struct SomeType;
impl SomeTrait for SomeType {}
fn rc_downcaster<A: 'static, B: ?Sized + 'static>(b: Rc<B>) -> Option<Rc<A>> {
if Any::type_id(&*b) == TypeId::of::<A>() {
Some(unsafe {
let p = Rc::into_raw(b);
Rc::from_raw(p as *const A)
})
} else {
None
}
}
fn main() {
let x: Rc<dyn SomeTrait> = Rc::new(SomeType);
let _: Rc<SomeType> = rc_downcaster(x).unwrap();
}