繁体   English   中英

如何从盒装特征创建特征对象?

[英]How to create trait object from boxed trait?

我想使用 DST 并具有以下场景

我有以下特性,它可以接收Box并在外部返回新的 Trait 对象:

pub trait MyTrait {
    fn create_from_box(boxed: Box<Self>) -> Self
    where
        Self: Sized;
}

我关注了正在实现MyTrait struct FirstStruct 的不同结构;

impl MyTrait for FirstStruct {
    fn create_from_box(boxed: Box<FirstStruct>) -> FirstStruct {
        FirstStruct // Build another struct with some logic and boxed struct values
    }
}

struct SecondStruct;

impl MyTrait for SecondStruct {
    fn create_from_box(boxed: Box<SecondStruct>) -> SecondStruct {
        SecondStruct // Build another struct with some logic and boxed struct values
    }
}

我有一个函数可以在某些条件逻辑中获取我的 trait 对象

fn get_my_trait_object() -> Box<MyTrait> {
    let condition = true; // Retrieved via some logic .

    match condition {
        true => Box::new(FirstStruct),
        false => Box::new(SecondStruct),
    }
}    

然后我有以下函数,它将我的特征对象作为装箱值,然后将其传递给MyTrait静态方法。

然后它尝试创建一个新的 MyTrait 对象,稍后将使用该对象。

pub fn main() {
    let boxed = get_my_trait_object();
    let desired_trait_object = MyTrait::create_from_box(boxed);
}

这里的主要问题是,当我执行代码时,出现以下两个不同的错误:

  • 在编译时无法知道dyn MyTrait类型的值的大小
  • 所有局部变量必须具有静态已知的大小

我该如何解决这些错误并实现我想要做的事情?

操场

即使您的类型被装箱(请参阅into_vec ),您也可以使用self ,因此您的解决方案可能是。

pub trait CreateFromBox {
    fn create_from_box(self: Box<Self>) -> Self;
}

#[derive(Debug, Clone)]
struct Foo(u32);
impl CreateFromBox for Foo {
    fn create_from_box(self: Box<Self>) -> Self {
        Self(self.0 + 1)
    }
}

fn main() {
    let a: Box<Foo> = Box::new(Foo(3));
    let tmp = a.clone();
    let b: Foo = tmp.create_from_box();

    println!("{:?} {:?}", a, b);
}

暂无
暂无

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

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