Iterator over Mutable Windows of Slice

windows_mut cannot be soundly implemented as an iterator even with unsafe code, due to limitations of the Iterator trait. Basically, because Self::Item can only be a single type, all returned items will have type &'a mut [T] with the same lifetime 'a, meaning their lifetimes will effectively overlap.

You can write something that is almost an iterator. Basically just a regular struct with a method like Iterator::next, except that the lifetime in the output is bound to a much shorter lifetime (the &mut self in next):

impl<'a, T> WindowsMut<'a, T> {
    fn next(&mut self) -> Option<&mut [T]> { ... }
}

and use it like

// can't use `for`; not an iterator
while let Some(window) = windows.next() {
    ...
}

I think this can be implemented in safe code even.

7 Likes