I have a struct AppData with contains a Vec<Box<Updatable>> called objects, which contains structs that implement a trait Updatable with the following function:
fn update(&mut self, data: &mut AppData) {
//default implementation accesses and mutates AppData, including the internal `objects` Vec and possibly also objects inside it
}
The AppData struct is stored in a field data in a struct App with the following function:
pub fn update(&mut self) {
for d in self.data.objects.iter(){
d.update(&mut self.data);
}
}
I cannot do this beacuse Box<T> is immutable. So I tried using indexers instead:
for i in 0..self.data.objects.len() {
let ref mut d = self.data.objects[i];
d.update(&mut self.data);
}
But then I get
cannot borrow
self.dataas mutable more than once at a time
So what do I do? I could probably get it to compile using combinations of RefCell etc but I'm not sure it would be idiomatic Rust. A few alternatives:
- Cloning the
Vecand iterating over the clone instead. But I ran into trouble becauseUpdateabledoes not implementSized. - Using
RefCellinstead ofBox. I'm not sure I should need it since I'm not storing the references to theVecinside theUpdatablesbut that might not make a difference? I supposeRefCellis supposed to be used overRcin this scenario because I want mutable references? Also this does not solve my problem because I still need to take ownership ofself.datasomehow, right? - Taking ownership of
self.dataafter deconstructingselfand then placing it back into self after we are done with it. How do I do that?
Thanks in advance!
data.objectsbe used inupdate? Or only other fields ofdata? - malbarbo