How can I iterate over a borrowed array?

I thought it should be something like this, but I cannot iterate over the 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 Rzhav 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());
                     ^~~~~~~~~~~~~~

      

+3


source to share


1 answer


An iterator is a regular object; you are working with the iterator directly, not usually through references, and of course not necessarily through immutable references, it takes the next iterator value to accept &mut self

. And a reference to an iterator is very different from an iterator over references.

By fixing this part, you get this:

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

      



However, this doesn't fix everything, because it [T].iter()

creates a type Iterator<Item = &T>

that iterates over the references to each element. The most common solution for this is to clone each value with a convenience method .cloned()

that is equivalent .map(|x| x.clone())

.

In this case, the rest of what you get is:

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

      

+3


source







All Articles