3

I thought that it should be something like this, but I cannot iterate over an borrowed array.

fn print_me<'a, I>(iter: &'a I) where I: Iterator<Item = i32> {
    for i in *iter {
        println!("{}", i);
    }
}

fn main() {
    let numbers = vec![1, 2, 3];
    //let numbers = &numbers;
    print_me(numbers.iter());
}

But Rust complains:

<anon>:15:12: 15:26 error: mismatched types:
 expected `&_`,
    found `core::slice::Iter<'_, _>`
(expected &-ptr,
    found struct `core::slice::Iter`) [E0308]
<anon>:15   print_me(numbers.iter());
                     ^~~~~~~~~~~~~~

1 Answer 1

4

An iterator is a regular object; you work with an iterator directly, not typically through references—and certainly not typically through immutable references, for taking the next value of an iterator takes &mut self. And a reference to an iterator is quite different from an iterator over references.

Fixing this part, you then have this:

fn print_me<I: Iterator<Item = i32>>(iter: I) {
    for i in iter {
        println!("{}", i);
    }
}

This doesn’t fix everything, however, because [T].iter() produces a type implementing Iterator<Item = &T>—it iterates over references to each item. The most common fix for that is cloning each value with the handy .cloned() method, which is equivalent to .map(|x| x.clone()).

Here, then, is the rest of what you end up with:

fn main() {
    let numbers = vec![1, 2, 3];
    print_me(numbers.iter().cloned());
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot. It does make sense. The other possibility is change a function as it use a reference.
@lofcek: it is not useful to take an iterator by mutable reference; if I implements Iterator, &mut I does too, so you can pass a mutable reference to an iterator in that way. There’s even the by_ref(&mut self) -> &mut Self method on Iterator for convenience of chaining.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.