Hello all,
I'm having a move out of shared reference
error when I try to return a trait object from an enum.
Let me show you:
trait Trait {}
impl Trait for String {}
enum E {
Int(i32),
Obj(Box<dyn Trait>)
}
impl E {
fn to_trait(&self) -> Box<dyn Trait> {
match self {
Self::Int(i) => Box::new(i.to_string()) as Box<dyn Trait>,
Self::Obj(o) => *o,
// ^^ move occurs because `*o` has type `std::boxed::Box<dyn Trait>`, which does not implement the `Copy` trait
}
}
}
If I try to change the to_trait
signature to return a reference &Box<dyn Trait>
, I get another error because I try to return a temporary object in the case of Int
:
impl E {
fn to_trait(&self) -> &Box<dyn Trait> {
match self {
Self::Int(i) => &(Box::new(i.to_string()) as Box<dyn Trait>),
// ------------------------------------------- temporary value created here
Self::Obj(o) => o,
}
// ^ returns a value referencing data owned by the current function
}
}
Is there a solution to my problem ?