我有以下实现草图:
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<dyn 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
,当该事务发生某些事情时,它们会调用监听器。由于Listener
是一个特征,我存储一个Vec<Box<Listener>>
.
我很难commit
实施Transaction
. 不知何故,我必须通过调用commit
每个存储Listener
的 s 来消耗这些盒子,但据我所知,我无法将东西移出盒子。
我将如何在提交时消耗我的听众?