I'm making a tile-based game with structures that span multiple tiles. Every tile under the structure has to have a mutable reference to that structure. For a structure that spans two tiles, the 2D array that represents the map has to simultaneously contain two mutable references to the structure.
I also have a list that mutably owns all my structures (for iteration)
I tried this with &mut
and failed:
let mut all_structures: Vec<Box<Structure>> = Vec::new();
let mut grid: [[Vec<&mut Box<Structure>>; 4]; 4] = Default::default(); // accessed [y][x]
let mut house: Box<Structure> = Box::new(House { });
grid[1][1].push(&mut house);
grid[1][2].push(&mut house);
all_structures.push(house);
with error:
error[E0499]: cannot borrow `house` as mutable more than once at a time
--> src/main.rs:21:21
|
20 | grid[1][1].push(&mut house);
| ---------- first mutable borrow occurs here
21 | grid[1][2].push(&mut house);
| ---- ^^^^^^^^^^ second mutable borrow occurs here
| |
| first borrow later used by call
Right now this is just single threaded so nothing needs to be thread-safe
I put the code on the playground