When attempting to create objects that inherit a trait from within a match
statement, I find it's necessary to define different external variables for every type of object being matched. It's necessary to declare the variables outside of the match so that the declarations don't go out of scope.
It's impossible to use a single external variable of type Trt
since Trt
is unsized. It there any way to have the match return an object implementing Trt
without reverting to this ugly method of defining lots of variables ahead of time?
Here's an example of the problem:
enum Enm {
X1,
X2,
X3
}
trait Trt {
fn foo(&self) -> &'static str;
}
struct A{}
impl Trt for A{
fn foo(&self) -> &'static str { "A" }
}
struct B{}
impl Trt for B{
fn foo(&self) -> &'static str { "B" }
}
struct C{}
impl Trt for C{
fn foo(&self) -> &'static str { "C" }
}
fn main() {
let x = Enm::X3;
let mut temp;
let mut temp2;
let mut temp3;
let gen = match x {
Enm::X1 => {
temp = A{};
&mut temp as &mut Trt
},
Enm::X2 => {
temp2 = B{};
&mut temp2 as &mut Trt
},
Enm::X3 => {
temp3 = C{};
&mut temp3 as &mut Trt
},
};
println!("{}", gen.foo());
}