New function suggestion: iter::take_exactly

I think there is a point in what the OP brings up, but having a panicky method should have a very nice name that expresses that. Given that the _exactly part does not apply for the "too many elements", as @djc points out, I personally think this is rather an issue with take not being named take_at_most. This could be fixed by adding that method with a default implementation (maybe through a super-trait to avoid overriding the impl) that'd defer to take, which would be deprecated.

Then, for those really wanting such a panicking variant, either they use ::itertools, or re-write the trivial implementation themselves:

- iterator.take_at_most(n)
+ (0 .. n).map(move |_| iterator.next().unwrap())
// or are the desired semantics to yield an `Option<Iterator>`?

As @H2CO3 points out, the different approaches have non-negligible semantic differences, so it's one of those cases, imho, where being (too) explicit is better than being too terse, at least as far as the std lib is concerned (::itertools can pick a choice and document it well).


FWIW, in the (very common) case of slices, writing v[.. len].iter().map(…)is both idiomatic and expresses what you want :slightly_smiling_face: (with [.. len].iter_mut() and {vec}.drain(.. len) for the by-mut and owned versions).

4 Likes