iterator - Why calling cloned() on Iter with inferred Item type allows it to be passed into this function? -


i trying learn little bit iterator , how works , hoping of explain me somthing code:

fn main() {     let a: vec<_> = (0..10).map(|_| 2).collect();     let = a.iter();     print(it); }  fn print<i: iterator<item=usize>>(iter: i) {     x in iter {         println!("{}",x);     } } 

i know code above convoluted, simples code ve created more complicated version in made more sense, find core of problem , understand better.

when compiling code in rustc have compile error:

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

i fixed changing let to:

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

or

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

as far understand error suggest compiler cannot safely inferr type of item trying pass argument, why calling cloned() or map changes anything?

your print function expects iterator of usizes argument, it (in first version) iterator yields &usize values, i.e. references usize.

cloned() maps clone::clone on iterator, transforms iterator of &t iterator of t, fixes type mismatch in program.

your final version (let = a.iter().map(|&x| x);) converts iterator iterator of &t iterator of t, time dereferencing elements using pattern matching.

since print doesn't need own elements of iterator, fix problem changing type following:

fn print<'a, i: iterator<item=&'a usize>>(iter: i) 

Comments

Popular posts from this blog

powershell Start-Process exit code -1073741502 when used with Credential from a windows service environment -

twig - Using Twigbridge in a Laravel 5.1 Package -

c# - LINQ join Entities from HashSet's, Join vs Dictionary vs HashSet performance -