Got an error when create cycle iterator from initial iterator passed by ref

Hi everyone !

I need to make cycle iterator from initial iterator which is passed to the function by reference.
But I got an error:

error[E0277]: the trait bound `&mut std::slice::Iter<'_, {integer}>: Clone` is not satisfied
    --> src/main.rs:5:32
     |
5    |     let mut cycle_iter = iter1.cycle();
     |                                ^^^^^ the trait `Clone` is not implemented for `&mut std::slice::Iter<'_, {integer}>`
     |
note: required by a bound in `cycle`
    --> /playground/.rustup/toolchains/stable-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/iter/traits/iterator.rs:3501:23
     |
3499 |     fn cycle(self) -> Cycle<Self>
     |        ----- required by a bound in this associated function
3500 |     where
3501 |         Self: Sized + Clone,
     |                       ^^^^^ required by this bound in `Iterator::cycle`
help: consider removing the leading `&`-reference
     |
4    -     let iter1 = &mut iter;
4    +     let iter1 = iter;
     |

I created small example to reproduce:

fn main() {
    let arr = vec![1, 2, 3, 4, 5];
    let mut iter = arr.iter();
    let iter1 = &mut iter;
    let mut cycle_iter = iter1.cycle();
    
    for i in 0..arr.len()*2 {
        println!("[]: {:?}", cycle_iter.next());
    }
}

And this is a sandbox: Rust Playground

Could someone explain how to fix this and why this error happened ?

&mut Iter<'_, T> does not implement Clone, thus it doesn't satisfy the Self: Clone bound on Iterator::cycle. You can fix this by creating a clone from the underlying Iter<'_, T> that you get passed by mutable reference first, before calling cylce. This works because Iter<'_, T> does implement Clone:

fn main() {
    let arr = vec![1, 2, 3, 4, 5];
    let mut iter = arr.iter();
    let iter1 = &mut iter;
    let mut cycle_iter = iter1.clone().cycle();
    
    for i in 0..arr.len()*2 {
        println!("[]: {:?}", cycle_iter.next());
    }
}

Playground.

2 Likes

As clearly stated by the error message, a mutable reference is not clone-able. (It can't be – if it were cloneable, that would violate the aliasing model of the language. Mutable references must always be exclusive.)

Just call cycle() on iter directly.

4 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.