我有一個實施的下列草圖:如何調用在盒裝特質對象上消耗自我的方法?
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