[英]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.