I am trying to do something that should be easy but I'm failing at it
I have a struct like the following one:
pub struct EntityList {
entities: Vec<Entity>,
to_add: Vec<Entity>,
to_awake: Vec<Entity>,
to_remove: Vec<Entity>,
}
and a function that should iterate over the to_add
vec and move those elements into the entities
vec actually changing the ownership of the elements.
pub fn update_lists(&mut self) {
if self.to_add.len() > 0 {
let mut i = 0;
for to_add_it in &mut self.to_add {
let entities_contains = self.entities.iter().any(|e| *e == *to_add_it);
if !entities_contains {
let elem = self.to_add.remove(i);
self.entities.push(elem);
to_add_it.entity_added();
to_add_it.awake();
}
i += 1;
}
self.to_add.clear();
}
}
but it's failing because I'm first borrowing it through the iterator and then trying to borrow it again with the call to remove
.
The actual error is the following:
error[E0499]: cannot borrow `self.to_add` as mutable more than once at a time
--> src/entitylist.rs:49:32
|
46 | for to_add_it in &mut self.to_add {
| ----------- first mutable borrow occurs here
...
49 | let elem = self.to_add.remove(i);
| ^^^^^^^^^^^ second mutable borrow occurs here
...
56 | }
| - first borrow ends here
There must be a better way to accomplish this. Any suggestion is welcome. Thanks in advance!