Move a Box inside a Struct

1.5k views Asked by At

I'm currently playing with Rust and I want to implement a sort-of State design pattern. For that, I need to have, as struct attributes, a Box of a trait.

Let's image State is my trait. It would be something like that.

pub trait State {
    // some functions
}

pub struct State1 {
    Box<State> s;
}

impl State for State1 {
    // some implementations
}

Another possibility:

pub struct State2 {
    HashMap<uint, Box<State>> hash;
}

impl State for State2 {
    // some implementations
}

Now, I can figure out what to do to initialize all of this. There are lifetime issues.

What I want, basically, is something like that:

impl State1 {
    pub fn new(s: Box<State1>) {
        State1 {
            s: ... // the value inside Box is moved and now owned
                   // by the new State1 object, so it won't be usable
                   // by the caller after this call and then safe
        }
    }
}

Is it possible?

Thanks by advance!

2

There are 2 answers

2
Manishearth On BEST ANSWER

You just need to cast to a trait object

impl State1 {
    pub fn new(s: Box<State1>) {
        State1 {
            s: s as Box<State>
        }
    }
}
0
lthms On
pub struct AutomateFeeder<'a> {
   automate: Box<Automate + 'a>,
}

impl<'a> AutomateFeeder<'a> {
    pub fn new<T: Automate + 'a>(automate: Box<T>) -> AutomateFeeder<'a> {
        AutomateFeeder {
            automate: automate as Box<Automate>,
        }
    }
}

This does the trick.