Why does calling cloned () on an Iter with the specified Item type allow it to be passed to this function?

I was trying to learn a little about the Iterator and how it works, and I was hoping that some of you could explain something to me about this code:

fn main() {
    let a: Vec<_> = (0..10).map(|_| 2).collect();
    let it = a.iter();
    print(it);
}

fn print<I: Iterator<Item=usize>>(iter: I) {
    for x in iter {
        println!("{}",x);
    }
}

      

I know the above code is very confusing, but its a simple code that I created from a much more complex version, in which it makes more sense, just to find the root of the problem and understand it better.

When compiling this code in rustc, I have this compilation error:

src/main.rs:5:5: 5:8 error: type mismatch resolving `<core::slice::Iter<'_, _> as core::iter::Iterator>::Item == usize`:
 expected &-ptr,
    found usize [E0271]
src/main.rs:5     print(it);
                  ^~~

      

I fixed this by changing let to:

let it = a.iter().cloned();

      

or

let it = a.iter().map(|&x| x);

      

As I understand it, the error says that the compiler cannot safely determine the type of the element I am trying to pass as an argument, but why does it trigger cloning () or map change?

+3


source to share


1 answer


The function print

expects an Iterator usize

as an argument, but it

(in your first version) is an iterator that gives values &usize

, that is, references to usize

.

cloned()

essentially maps Clone::clone

over an iterator, so it converts the iterator &T

to an iterator T

, so that fixes the type mismatch in your program.

Your final version ( let it = a.iter().map(|&x| x);

) will also convert the iterator from an iterator &T

to an iterator T

, but this time dereferencing the elements using pattern matching.



Since print

you don't actually need to own the elements of the iterator, you can also fix your problem by changing its type to the following:

fn print<'a, I: Iterator<Item=&'a usize>>(iter: I)

      

+2


source







All Articles