【发布时间】:2014-11-20 00:51:47
【问题描述】:
我目前正在玩 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
}
}
}
有可能吗?
提前致谢!
【问题讨论】: