I am currently reading a longer chapter about iterators.
My feeling was, that map() and cloned() produces a value, so I assumed that the two commented out lines in the example below would be correct. But they do not compile:
let numbers = [1, 2, 3, 4, 5];
let processed: Vec<i32> = numbers
.iter()
.map(|x| *x * 2) // now the item is a value?
.filter(|&x| x > 5) // this works
//.filter(|x| x > 5) // but why does this fail
.collect();
println!("{:?}", processed);
let numbers = [1, 2, 3, 4, 5];
let processed: Vec<i32> = numbers
.iter()
.cloned() // now the item is a value?
.filter(|x| *x > 5) // this works
//.filter(|x| x > 5) // but why does this fail
.collect();
println!("{:?}", processed);
One more question: The API docs say that we should use cloned() as late as possible when chaining iterator adaptors for best performance. I would also assume, that we should use adaptors like filter() early to reduce the number of items, before doing other operations like map()?