I'm trying to return an iterator without the last element of the input slice, and I need it to work on empty arrays as well. I've coded up two versions:

let all_but_one = if slice.len() > 0 { slice.len() - 1 } else { 0 };

slice.into_iter().take(all_but_one)
// slice.into_iter().take(slice.len()-1) would crash on an empty slice

and

slice.into_iter().rev().skip(1).rev()

I aesthetically like the second better, but I suspect it's slower (especially in the first iteration, since it has to go over the entire list). Is my fear correct? Is there a prettier version that's as cheap as the first?

1 post - 1 participant

Read full topic

Source: View source