Add Iter::cloned() fn to Enumarate

cloned could be implemented on the Enumerate struct so the same it ensures the same coding style when trying to clone late as the docs suggest. Since there is no clone on Enumerate someone will have to clone the whole collection first then do the filtering.

Take a look at the docs suggestion

let slower: Vec<_> = a.iter().cloned().filter(|s| s.len() == 1).collect();
assert_eq!(&[vec![23]], &slower[..]);
// instead call `cloned` late
let faster: Vec<_> = a.iter().filter(|s| s.len() == 1).cloned().collect();
assert_eq!(&[vec![23]], &faster[..]);

let faster: Vec<_> = a.iter().enumerate().filter(|s| s.len() == 1).cloned().collect(); // This is not possible

Forced to do this instead

let not_faster: Vec<_> = a.clone().iter().enumerate().filter(|s| s.len() == 1).collect() //<- forced to do this

Making Enumerate clone wouldn't enable .cloned() to work on it, because in order to use that, the Iterator item type must be &T. But Enumerate has an item type of (usize, &T) in your case.

I think the best option for this case is to just do

let faster: Vec<_> = a.iter()
    .enumerate()
    .filter(|s| s.len() == 1)
    .map(|(i, x)| (i, x.clone()))
    .collect();
2 Likes

Any reason cloned() can’t be added as an intrinsic method, though? It’s still a convenience for map, so maybe it doesn’t pull its weight, but it should be possible, right?

4 Likes

It sounds like the actual thing that would help here is a method that clones members of tuples in an iterator. I've had to write things like .map(|(i, x)| (i, x.clone())) many times, and I've often felt like there should be a more convenient way, although I'm not sure how that could actually be accomplished (since there are many variations of which fields you want to clone and which you don't – would we have multiple methods?).

(Literally speaking, it doesn't even help to implement this on Enumerate, because once you call filter, the iterator is a Filter instead of an Enumerate. And you'd want a solution that generalizes over other types like FilterMap too.)

5 Likes

do you think this is worth it to start looking into it?

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.