Reputation: 519
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!
Upvotes: 0
Views: 1545
Reputation: 519
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.
Upvotes: 1
Reputation: 16188
You just need to cast to a trait object
impl State1 {
pub fn new(s: Box<State1>) {
State1 {
s: s as Box<State>
}
}
}
Upvotes: 1