繁体   English   中英

如何从盒装特征 object 中获取对结构的引用?

[英]How to get reference to struct from boxed trait object?

我想将Box<T>类型的值插入到Vec<Box<Trait>>中,然后获取对该值的引用。 T是实现Trait的通用类型)。 返回值的类型应该是&T

下面的实现几乎可以工作,除了无法Box<Trait>转换为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 {
}

您现在可以在从矢量获得的&dyn A上调用.as_any()

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!(),
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM