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!
You just need to cast to a trait object