0

I wrote something which I've been using to combine itertools sort+group.

pub trait SortAndGroup: Iterator {
    fn sort_and_group<K>(self, key_selector: fn(&Self::Item) -> K) -> Vec<(K, Vec<Self::Item>)>
    where
        Self: Sized,
        K: Ord,
    {
        self.sorted_by_key(key_selector)
            .group_by(key_selector)
            .into_iter()
            .map(|(k, g)| (k, g.into_iter().collect::<Vec<_>>()))
            .collect::<Vec<_>>()
    }
}

impl<T: ?Sized> SortAndGroup for T where T: Iterator { }

I usually want to invoke it on some vec and then do some additional mapping and filtering.

Let's say I use it like this:

files
    .iter()
    .sort_and_group(|f| f.joint_folder.clone())
    .into_iter()
    .map(|(joint_folder, g)| {

I'm annoyed that I always have to convert the vec with iter() before calling this and again afterwards call into_iter() on it.

Can I change my trait to have the function callable directly on the Vec and to return something on which I can immediately call map without having to convert the returned value into iterator?

I want to be able to do something like this:

files
    .sort_and_group(|f| f.joint_folder.clone())
    .map(|(joint_folder, g)| {
Makyen
  • 31,849
  • 12
  • 86
  • 121
ditoslav
  • 4,563
  • 10
  • 47
  • 79
  • Does this answer your question? [What is the correct way to return an Iterator (or any other trait)?](https://stackoverflow.com/questions/27535289/what-is-the-correct-way-to-return-an-iterator-or-any-other-trait) – kmdreko Mar 26 '21 at 18:18
  • @kmdreko I think the issue here is that you can't return `impl Iterator` from a trait method. – Peter Hall Mar 26 '21 at 18:34
  • @PeterHall True, but one portion of the answer there suggests `Box` which *is* allowed for a trait method. – kmdreko Mar 26 '21 at 18:36
  • Can I at least be able to run directly on Vec? – ditoslav Mar 29 '21 at 15:05
  • Can I somehow map over the boxed iterator directly or do I have to unbox later? – ditoslav Mar 29 '21 at 15:06

0 Answers0