I want to work with DST's and having the following scenario
I have the following trait which has ability to take Box
and return new Trait Object outside:
pub trait MyTrait {
fn create_from_box(boxed: Box<Self>) -> Self
where
Self: Sized;
}
I have following to different structs which are implementing 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
}
}
I have a function which gets my trait object in some conditional logic
fn get_my_trait_object() -> Box<MyTrait> {
let condition = true; // Retrieved via some logic .
match condition {
true => Box::new(FirstStruct),
false => Box::new(SecondStruct),
}
}
Then I have the following function which gets my trait object as boxed value and then passes it into MyTrait
static method.
And then it tries to create a new MyTrait object which will used later on.
pub fn main() {
let boxed = get_my_trait_object();
let desired_trait_object = MyTrait::create_from_box(boxed);
}
The main problem here is, when I executed the code I get following two different errors:
- The size for values of type
dyn MyTrait
cannot be known at compilation time - All local variables must have a statically known size
How can I solve these errors and achieve what I am trying to do?