I'm working with a lot of 2d vectors, and it gets annoying to write
for y in (0..self.array.len()).rev() {
for x in 0..self.array[y].len() {
if let Some(tile) = self.get_tile(x, y) {
...
}
}
}
so i want to make a closure to make this less indented
fn for_tile<T: Fn(&Tile, usize, usize)>(&self, function: T) {
for y in (0..self.array.len()).rev() {
for x in 0..self.array[y].len() {
if let Some(tile) = self.get_tile(x, y) {
function(&tile, x, y);
}
}
}
}
this compiles, but i get errors when i try to use it like this:
self.for_tile(|tile, x, y| {
if !tile.enabled {
self.erase_tile(*tile, x, y)
}
});
i get this error:
error[E0596]: cannot borrow `*self` as mutable, as it is a captured variable in a `Fn` closure
--> src/main.rs:85:17
|
85 | self.erase_tile(*tile, x, y)
| ^^^^ cannot borrow as mutable
error[E0500]: closure requires unique access to `*self` but it is already borrowed
--> src/main.rs:83:24
|
83 | self.for_tile(|tile, x, y| {
| ---- --------- ^^^^^^^^^^^^^ closure construction occurs here
| | |
| | first borrow later used by call
| borrow occurs here
84 | if !block.enabled {
85 | self.erase_tile(*tile, x, y)
| ---- second borrow occurs due to use of `*self` in closure