【发布时间】:2020-10-11 23:34:38
【问题描述】:
我需要编写一个函数foo,它接受&RefCell<Box<dyn Any>>,从RefCell 借用并返回一个向下转换的对象。向下转换的类型是在运行时选择的,但对于本例,我们假设它是 usize。
use core::any::Any;
use std::cell::{RefCell, Ref};
pub fn foo<T: 'static>(cell: &RefCell<Box<dyn Any>>) -> Option<Ref<Box<T>>> {
???
}
pub fn main() {
let boxed: Box<dyn Any> = Box::new(1 as usize);
let cell = RefCell::new(boxed);
let num = foo(&cell);
println!("x: {}", num.unwrap());
}
我尝试像这样实现foo:
// 1:
pub fn foo<T: 'static>(cell: &RefCell<Box<dyn Any>>) -> Option<Ref<Box<T>>> {
let borrowed_cell = Ref::map(cell.borrow(), |borrow| borrow.downcast_ref::<T>().unwrap());
Some(borrowed_cell)
}
这个版本的问题在于它假定downcast_ref 将始终有效,但我想捕捉downcast_ref 错误。
下面我尝试以可以捕获错误的方式实现foo:
// 2:
pub fn foo<T: 'static>(cell: &RefCell<Box<dyn Any>>) -> Option<Ref<T>> {
{
cell.borrow().downcast_ref::<T>()?;
}
let borrowed_cell = Ref::map(cell.borrow(), |borrow| borrow.downcast_ref::<T>().unwrap());
Some(borrowed_cell)
}
这个版本可以捕获downcast错误,但它必须调用downcast_ref两次(这可以接受,但我想知道是否有更好的方法)。当尝试只使用一次 downcast_ref 时,我遇到了终身错误。
【问题讨论】:
标签: rust traits ref downcast refcell