`positions()` method for slices, or iterators in general

I recently came across a situation where I wanted to get the indices of each occurrence of a value in a slice. Basically, something like str.match_indices, but for a &[u8]. I was surprised to learn that there wasn’t anything like that in the standard library. The best thing I could find would be to do something like

slice.iter().enumerate().filter(|(_,x)| x == needle).map(|(i,_)| i)

I expected there to be something like

slice.iter().positions(|x| x == needle)

Do you think a positions method should be added to Iterator in the standard library? Or to slice? If so, I’d be happy to make a PR and/or RFC.

  • Include Iterator.positions to standard library
  • Add slice.positions to standard library
  • This doesn’t belong in the standard library

0 voters

There’s an issue open on itertools to add exactly this method to it: https://github.com/bluss/rust-itertools/issues/218

I think it would be best to see how much it gets used in practice before deciding to add that method, which is just syntactic sugar for a combination of methods and which can’t be improved over the default impl for any implementation

3 Likes

Looks like came up with the same idea at the same time… we have the interest needed to put it into itertools! (I voted std. lib. anyway.)

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