I want to design a toy container class with support for mutable iterators, but I'm having trouble sorting out the lifetimes of the iterator and its reference to the container.
I've tried to create a minimal non-compiling example:
struct Payload { value: i32, } struct Container { val: Payload, } struct IterMut<'a> { cont: &'a mut Container, cnt: i32, } impl<'a> Container { fn new() -> Container { Container { val: Payload { value: 42 } } } fn iter_mut(&'a mut self) -> IterMut<'a> { IterMut { cont: self, cnt: 10, } } } impl<'a> Iterator for IterMut<'a> { type Item = &'a mut Payload; fn next<'b>(&'b mut self) -> Option<Self::Item> { self.cnt -= 1; if self.cnt < 0 { return None; } else { Some(&mut self.cont.val) } } } fn main() { let mut cont = Container::new(); let mut it = cont.iter_mut(); it.next(); } The above is intended to implement a real stupid container that returns the same item 10 times when iterated over using iter_mut().
I can't figure out how to implement Iterator::next.
I did manage to write a regular function that implements the same semantics as what I want for next:
fn manual_next<'a, 'b>(i: &'a mut IterMut<'b>) -> Option<&'a mut Payload> { i.cnt -= 1; if i.cnt < 0 { return None; } else { Some(&mut i.cont.val) } } This doesn't help, because I can't manage to adapt it to implement Iterator::next, and without implementing Iterator, my container can't be iterated over in for-loops, which I want.