lofcek
lofcek

Reputation: 1233

How I can iterate over borrowed array?

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());
                     ^~~~~~~~~~~~~~

Upvotes: 3

Views: 1566

Answers (1)

Chris Morgan
Chris Morgan

Reputation: 90712

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());
}

Upvotes: 4

Related Questions