我目前正在玩Rust,我想实现一种状态设计模式。为此,我需要作为结构属性获得一个特征框。
让我们的图像State
成为我的特质。就像那样。
pub trait State {
// some functions
}
pub struct State1 {
Box<State> s;
}
impl State for State1 {
// some implementations
}
另一种可能性:
pub struct State2 {
HashMap<uint, Box<State>> hash;
}
impl State for State2 {
// some implementations
}
现在,我可以弄清楚要做什么来初始化所有这些。有终身问题。
基本上,我想要的是:
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
}
}
}
有可能吗?
先谢谢!
答案 0 :(得分:1)
你只需要转换为特质对象
impl State1 {
pub fn new(s: Box<State1>) {
State1 {
s: s as Box<State>
}
}
}
答案 1 :(得分:1)
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>,
}
}
}
这就是诀窍。