2017-07-25 32 views
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 

回答

2

keys() method返回在HashMap中的密鑰的迭代器。 clone()調用只複製迭代器,但不是密鑰本身。您使用map函數的原始方法看起來很有希望。你可能需要使用collect() method of the iterator收集結果在Vec

let keys = self.components.keys().cloned().collect::<Vec<_>>(); 

然後:

for key in keys { 
    self.components.remove(&key).unwrap(); 
} 

這確保了切除手術開始前所有的按鍵都被複制。

+0

感謝您的幫助。那就是訣竅。我真的很感激 –

+3

我會說'self.components.keys()。clone()。collect()'是首選。 – Shepmaster