【发布时间】:2018-03-19 03:33:57
【问题描述】:
我有以下实现的草图:
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();
}
我可以让Transactions 带有监听器,当该事务发生某些事情时,它们会调用监听器。由于Listener 是一个特征,我存储了一个Vec<Box<Listener>>。
我很难为Transaction 实施commit。不知何故,我必须通过在每个存储的 Listeners 上调用 commit 来消耗这些盒子,但据我所知,我无法将东西移出盒子。
我将如何在提交时使用我的听众?
【问题讨论】:
-
从盒子中取出“东西”很容易; you just dereference it。您的情况更复杂,因为您不再知道盒子内存储的值有多大。这意味着您会收到一个错误:无法移动侦听器类型的值:无法静态确定侦听器的大小。