Iterate through copies instead of refferences?


I have a function that accepts an iterator of usizes and I want to call it with the values in a Box<[usize]>:

fn something<L: Iterator<Item=usize>>(limits: L) -> Self {...}

However, both [usize].iter() and [usize].into_iter() return iterators that generate references to the values, instead of copies of the values, so I have to map the iterator with |&i| i before calling the function with it:

something(boxed_usize.into_iter().map(|&i| i)))

But this is slow right? It’s making a reference that it doesn’t need because it gets turn into a copy anyways.

My questions are: Why doesn’t Box<[usize]>'s into_iter() try to move out (or in this case copy) the values like Vec's into_iter() does? And does this reference actually get created if I instantly turn it into a copy, or does the compiler optimize this out?


[usize] is not an owner of the data, it’s just a view (slice) into some contiguous range that’s owned elsewhere. It can’t move anything out of there since it doesn’t own it.

I wouldn’t worry about the speed here, at least in the way you’re looking at it. If you want to avoid the map call, you can do something(boxed_usize.iter().cloned()) (see


Also, there’s a method on Iterator called cloned that you can use instead of mapping.