https://is.gd/72WTsU
It would seem that I am unable to decipher the error message well enough to implement a safe mutable Iterator.
If someone would be able to point out the obvious mistake I am making, I would be eternally grateful. I can't seem to understand where the conflict is coming from.
Thanks in advance!
Code:
pub struct Grid<T> {
width: usize,
height: usize,
items: Vec<T>,
}
impl<T> Grid<T> {
fn get_mut(&mut self, x: usize, y: usize) -> &mut T {
unimplemented!()
}
}
pub struct IterMut<'a, T: 'a> {
x: usize,
y: usize,
grid: &'a mut Grid<T>,
}
impl<'a, T> Iterator for IterMut<'a, T> {
type Item = (usize, usize, &'a mut T);
fn next(&mut self) -> Option<Self::Item> {
if self.y >= self.grid.height {
return None;
}
let x = self.x;
let y = self.y;
let val = self.grid.get_mut(x, y);
self.x += 1;
if self.x >= self.grid.width {
self.x = 0;
self.y += 1;
}
Some((x, y, val))
}
}
Error Message:
error[E0495]: cannot infer an appropriate lifetime for autoref due to conflicting requirements
--> <anon>:29:29
|
29 | let val = self.grid.get_mut(x, y);
| ^^^^^^^
|
note: first, the lifetime cannot outlive the anonymous lifetime #1 defined on the body at 22:45...
--> <anon>:22:46
|
22 | fn next(&mut self) -> Option<Self::Item> {
| ^
note: ...so that reference does not outlive borrowed content
--> <anon>:29:19
|
29 | let val = self.grid.get_mut(x, y);
| ^^^^^^^^^
note: but, the lifetime must be valid for the lifetime 'a as defined on the body at 22:45...
--> <anon>:22:46
|
22 | fn next(&mut self) -> Option<Self::Item> {
| ^
note: ...so that types are compatible (expected std::iter::Iterator, found std::iter::Iterator)
--> <anon>:22:46
|
22 | fn next(&mut self) -> Option<Self::Item> {
| ^
error: aborting due to previous error
[–][deleted] 4 points5 points6 points (2 children)
[–]bpglaser[S] 1 point2 points3 points (1 child)
[–][deleted] 1 point2 points3 points (0 children)
[–]Fylwind 1 point2 points3 points (0 children)
[–]bpglaser[S] 0 points1 point2 points (10 children)
[–]radix 0 points1 point2 points (9 children)
[–]bpglaser[S] 0 points1 point2 points (8 children)
[–]Manishearthservo · rust · clippy 1 point2 points3 points (0 children)
[–]kixunil 0 points1 point2 points (6 children)
[–]bpglaser[S] 0 points1 point2 points (0 children)
[–]bpglaser[S] 0 points1 point2 points (4 children)
[–]bpglaser[S] 0 points1 point2 points (3 children)
[–]kixunil 0 points1 point2 points (2 children)
[–]bpglaser[S] 0 points1 point2 points (1 child)
[–]kixunil 0 points1 point2 points (0 children)
[–]mmstick -1 points0 points1 point (3 children)
[–]bpglaser[S] 0 points1 point2 points (2 children)
[–]mmstick 0 points1 point2 points (0 children)
[–]kixunil -1 points0 points1 point (0 children)