我有一个实施的下列草图:如何调用在盒装特质对象上消耗自我的方法?
trait Listener {
fn some_action(&mut self);
fn commit(self);
}
struct FooListener {}
impl Listener for FooListener {
fn some_action(&mut self) {
println!("{:?}", "Action!!");
}
fn commit(self) {
println!("{:?}", "Commit");
}
}
struct Transaction {
listeners: Vec<Box<Listener>>,
}
impl Transaction {
fn commit(self) {
// How would I consume the listeners and call commit() on each of them?
}
}
fn listener() {
let transaction = Transaction {
listeners: vec![Box::new(FooListener {})],
};
transaction.commit();
}
我可以有Transaction
s的对他们的听众,将调用监听器当事情发生在该交易。由于Listener
是一个特征,我存储Vec<Box<Listener>>
。
我很难实现commit
为Transaction
。不知何故,我必须通过在每个存储的Listener
上调用commit
来消费这些盒子,但据我所知,我无法将盒子移出盒子。
我会如何消费我的听众提交?
将“东西”移出盒子很容易; [你只需解除引用](https://stackoverflow.com/questions/42264041/how-do-i-get-an-owned-value-out-of-a-box)。你的情况更复杂,因为你不再知道存储箱内存储的值有多大。这意味着你会收到一个错误:*无法移动类型监听器的值:监听器的大小不能静态确定*。 – Shepmaster