I struggle with iterator which also mutates other fields of it's owner.
I've re-created a simplified example Playground:
#[derive(PartialEq)]
enum ResourceEnum {
Food,
}
struct Resource {
r#type: ResourceEnum,
amount: u32,
}
trait Building {
fn produce(&self) -> Option<Resource>;
}
struct Farm {}
struct City {
buildings: Vec<Box<dyn Building>>,
resources: Vec<Resource>,
}
impl City {
fn add_resource(&mut self, received: Option<Resource>) {
if let Some(received) = received {
if let Some(mut res) = self
.resources
.iter_mut()
.find(|r| r.r#type == received.r#type)
{
res.amount += received.amount;
} else {
self.resources.push(received);
}
}
}
}
impl Building for Farm {
fn produce(&self) -> Option<Resource> {
Some(Resource {
r#type: ResourceEnum::Food,
amount: 10,
})
}
}
fn main() {
let mut city = City {
buildings: vec![],
resources: vec![],
};
city.buildings.iter().for_each(|f| {
city.add_resource(f.produce());
});
}
Error:
error[E0502]: cannot borrow `city` as mutable because it is also borrowed as immutable
--> src/main.rs:55:36
|
53 | city.buildings.iter().for_each(|f| {
| -------------- -------- ^^^ mutable borrow occurs here
| | |
| | immutable borrow later used by call
| immutable borrow occurs here
54 | city.add_resource(f.produce());
| ---- second borrow occurs due to use of `city` in closure
What I'm trying to achieve is to have a single struct holding my 'world' -> City, which holds buildings like farms and all it's available resources like food.
At each state update I want to compute harvest from all farms and so on... and add produced resources into City storage, but can't figure out a way without storing all production as a separate Vector and iterating over it once again to just add it into City storage which seems redundant.
I guess I struggle to find a better way to design a structure of my world, but can't think of anything.