Another case of "cannot borrow `X` as mutable more than once at a time"

here is a snippet of my code. If it does not have enough context I will paste all my code, let me know.

I am using specs to build a simulation.

    fn run(&mut self, (entities, food_storage, maker_storage, mut offer_storage): Self::SystemData) {
            for (entity, food, maker, offer_opt) in (&entities, &food_storage, &maker_storage, (&mut offer_storage).maybe()).join(){
                println!("Hello, {:?}", &entity);
                match (offer_opt) {
                    Some (offer) =>
                        println!("{:?} has an offer", &entity),
                    None => {
                        println!("{:?} has no offer, adding one", &entity);
                        offer_storage.insert(entity, Offer{lot_size: Food(4.0), price: 1.0});
                    }
                }
            }
        }

The problem is with the line
offer_storage.insert(entity, Offer{lot_size: Food(4.0), price: 1.0});
Because offer_storage has already been mutably borrowed a few lines up, I can't mutably borrow it again.

From this answer that the solution is to "restructure the code so it doesn't have such borrowing patterns". It is not clear to me how I should accomplish this given that I only want to insert an offer when one doesn't already exist.

Caveat: I've never worked with specs.

Try looping once to collect entities without offers, and a second time to insert new offers. Or if offer_storage offers something like HashMap's Entry api, you can use that.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.