2017-07-25 5 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ハッシュマップ内のキーの反復子を返します。 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().cloned()。collect()'が好まれます。 – Shepmaster

関連する問題