The following pattern will never work out the way you want:
fn …<'a>(&'a self) -> &'a …
You use this pattern here:
fn get_mut<'a>(&'a mut self, x: usize, y: usize) -> Option<&'a mut T> { … }
fn iter_mut<'a>(&'a mut self) -> IterMut<'a, T> { … }
The moment you reach out to this pattern, what you'd have to do instead is using a closure with higher-rank trait bounds (HRTB):
fn get_mut(&mut self, x: usize, y: usize, f: F)
where
for<'scope_only> F: FnOnce(Option<&'scope_only mut T>)
{
f(self.data.get_mut(y)?.get_mut(x))
}
fn iter_mut(&mut self, f: F)
where
for<'scope_only> F: FnOnce(IterMut<'scope_only, T>)
{
f(IterMut {
grid: self,
step: 0..AREA,
})
}
The lifetime 'scope_only
defined by for<'scope_only>
only lives inside the closure, i.e. it cannot escape the closure.
If you try to change your remaining code to use these functions as I've changed, you'll either see it works or you'll realize, that you're trying to extend the lifetime beyond its scope, which is impossible, e.g. because you're trying to return the lifetime from a function.
You can try to apply the closure trick recursively (move the return type into a closure as an argument) until you either have working code or you get to the point where your code really begs for having the lifetime escape its prison and you cannot put your code inside the closure. The latter case means, you have to search for a different solution, because HRTB can only get you so far.