我想将Box<T>
类型的值插入Vec<Box<Trait>>
中,然后返回对该值的引用。 (T
是实现Trait
的通用类型)。返回的值应为&T
类型
下面的实现几乎可以正常工作,除了无法使用convert Box<Trait>
to Box<Any>
之外。HashSet
具有(实验性的)get_or_insert()
,非常适合此操作,但是Vec
似乎没有版本?
use std::any::Any;
trait A {}
struct B;
impl A for B {}
// How to write this function?
pub fn insert<'a, T>(vector: &mut Vec<Box<dyn A>>, value: T) -> &'a T where T: A {
// move the value into the vector
vector.push(Box::new(value));
// get the reference to the inserted value back
let it: &Box<dyn Any> = vector.last().unwrap(); // compile error
match it.downcast_ref::<T>() {
Some(i) => i,
None => panic!(),
}
}
fn main() {
let mut vec: Vec<Box<dyn A>> = Vec::new();
let b = B;
let b_ref = insert(&mut vec, b);
// can't use b here since moved, so need b_ref
}
最佳答案
您可以定义针对所有类型实现的帮助程序特征,如下所示:
pub trait AToAny: 'static {
fn as_any(&self) -> &dyn Any;
}
impl<T: 'static> AToAny for T {
fn as_any(&self) -> &dyn Any {
self
}
}
然后要求将其实现为A的子类型。pub trait A: AToAny {
}
现在,您可以在从矢量获得的.as_any()
上调用&dyn A
。pub fn insert<'a, T: A>(vector: &'a mut Vec<Box<dyn A>>, value: T) -> &'a T {
vector.push(Box::new(value));
let it: &dyn Any = vector.last().unwrap().as_any();
match it.downcast_ref::<T>() {
Some(i) => i,
None => panic!(),
}
}
关于generics - 如何从盒装特征对象获取对结构的引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65447332/