Cycle an IterMut?

Is there an idiomatic way to get the equivalent of x.iter_mut().cycle()? (Say x is a slice.) This doesn't compile because cycle requires Clone.

There can't be, since any Iterator can be collected, that is, all the items emitted by it must be able to coexist.

2 Likes

You can do something LendingIterator-esque for that particular case.

pub struct CycleSlice<'a, T> {
    slice: &'a mut [T],
    idx: Cycle<Range<usize>>,
}

impl<'a, T> CycleSlice<'a, T> {
    pub fn new(slice: &'a mut [T]) -> Self {
        let idx = (0..slice.len()).cycle();
        Self { slice, idx }
    }
    
    pub fn next(&mut self) -> Option<&mut T> {
        self.slice.get_mut(self.idx.next()?)
    }
}
2 Likes