gpt4 book ai didi

rust - 将 Ref> 向下转换为 Ref> 时处理向下转换错误

转载 作者:行者123 更新时间:2023-12-03 11:29:41 32 4
gpt4 key购买 nike

我需要写一个函数 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只有一次,我陷入了一生的错误。

最佳答案

经过一番修改后,我想出了这个解决方案。您可以使用 Any::is<T>()在映射之前检查借用。

pub fn foo<T: 'static>(cell: &RefCell<Box<dyn Any>>) -> Option<Ref<T>> {
let borrowed = cell.borrow();

if borrowed.is::<T>() {
Some(Ref::map(borrowed, |x| x.downcast_ref::<T>().unwrap()))
} else {
None
}
}
Rust Playground link

关于rust - 将 Ref<Box<dyn Any>> 向下转换为 Ref<Box<T>> 时处理向下转换错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64310019/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com