2

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());
}
Ameo
  • 2,307
  • 5
  • 21
  • 33

1 Answers1

2

The object you create needs to have an owner. Plain reference & can not be owner, that's why you need temp/temp2/temp3 in your code to serve as owner of the object you create in match arms.

The simplest way to own a trait object is to use Box like below:

// definitions omitted...
fn main() {
    let x = Enm::X3;

    let gen = match x {
        Enm::X1 => {
            Box::new(A{}) as Box<Trt>
        },
        Enm::X2 => {
            Box::new(B{}) as Box<Trt>
        },
        Enm::X3 => {
            Box::new(C{}) as Box<Trt>
        },
    };

    println!("{}", gen.foo());
}

After the match clause, now gen owns the created trait object, so you don't have to define temporaries anymore.

WiSaGaN
  • 46,887
  • 10
  • 54
  • 88
  • Ahh, thinking of everything having to have an owner makes it a lot more clear. Thanks for the great reply! – Ameo Oct 25 '16 at 02:04