0
我有一個Element
結構,它實現了一個採用滴答持續時間的更新方法。該結構包含一個組件向量。這些組件可以修改更新中的元素。我在這裏得到一個借用錯誤,我不知道該怎麼做。我試圖用塊來修復它,但是塊似乎並不滿足借用檢查器。在借用自我時在HashMap上出現鏽跡線
use std::collections::HashMap;
use std::time::Duration;
pub struct Element {
pub id: String,
components: HashMap<String, Box<Component>>,
}
pub trait Component {
fn name(&self) -> String;
fn update(&mut self, &mut Element, Duration) {}
}
impl Element {
pub fn update(&mut self, tick: Duration) {
let keys = {
(&mut self.components).keys().clone()
};
for key in keys {
let mut component = self.components.remove(key).unwrap();
component.update(self, Duration::from_millis(0));
}
}
}
fn main() {}
的誤差
error[E0499]: cannot borrow `self.components` as mutable more than once at a time
--> src/main.rs:20:33
|
17 | (&mut self.components).keys().clone()
| --------------- first mutable borrow occurs here
...
20 | let mut component = self.components.remove(key).unwrap();
| ^^^^^^^^^^^^^^^ second mutable borrow occurs here
...
23 | }
| - first borrow ends here
error[E0499]: cannot borrow `*self` as mutable more than once at a time
--> src/main.rs:21:30
|
17 | (&mut self.components).keys().clone()
| --------------- first mutable borrow occurs here
...
21 | component.update(self, Duration::from_millis(0));
| ^^^^ second mutable borrow occurs here
22 | }
23 | }
| - first borrow ends here
感謝您的幫助。那就是訣竅。我真的很感激 –
我會說'self.components.keys()。clone()。collect()'是首選。 – Shepmaster