borrow checker - Rust loop on HashMap while borrowing self -
i have element
struct implements update method takes tick duration. struct contains vector of components. these components allowed modify element on update. i'm getting borrow error here , i'm not sure do. tried fixing block, block doesn't seems satisfy borrow checker.
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() }; key in keys { let mut component = self.components.remove(key).unwrap(); component.update(self, duration::from_millis(0)); } } } fn main() {}
the error
error[e0499]: cannot borrow `self.components` mutable more once @ 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` mutable more once @ 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
the keys()
method returns iterator on keys in hashmap. clone()
call duplicates iterator, not keys themselves. original approach map
function looks promising. need collect result in vec
using collect()
method of iterator:
let keys = self.components.keys().cloned().collect::<vec<_>>();
and then:
for key in keys { self.components.remove(&key).unwrap(); }
this ensures keys copied before removal operation starts.
Comments
Post a Comment