Getting data back out of itertools group_by method

I can't figure out how to use the itertools group_by() method because the struct it returns does not implement many default traits. I am trying to collect the groups into a vec. I know the fold() approach is dumb but collect() is not implemented.

extern crate itertools; // 0.7.8
use itertools::Itertools;

fn main() {
    let mut data = vec![(1, 5), (9, 0), (8, 2), (1,0)];
    data.sort();
    let group = data.iter().group_by(|x| x.0);
    let gs = group.into_iter().fold(vec![], |mut a, b| {a.push(b); a});
    println!("{:?}", gs)
}
    


(Playground)

Errors:

   Compiling playground v0.0.1 (file:///playground)
error[E0277]: `itertools::Group<'_, {integer}, std::slice::Iter<'_, ({integer}, {integer})>, [closure@src/main.rs:7:38: 7:45]>` doesn't implement `std::fmt::Debug`
 --> src/main.rs:9:22
  |
9 |     println!("{:?}", gs)
  |                      ^^ `itertools::Group<'_, {integer}, std::slice::Iter<'_, ({integer}, {integer})>, [closure@src/main.rs:7:38: 7:45]>` cannot be formatted using `{:?}` because it doesn't implement `std::fmt::Debug`
  |
  = help: the trait `std::fmt::Debug` is not implemented for `itertools::Group<'_, {integer}, std::slice::Iter<'_, ({integer}, {integer})>, [closure@src/main.rs:7:38: 7:45]>`
  = note: required because of the requirements on the impl of `std::fmt::Debug` for `({integer}, itertools::Group<'_, {integer}, std::slice::Iter<'_, ({integer}, {integer})>, [closure@src/main.rs:7:38: 7:45]>)`
  = note: required because of the requirements on the impl of `std::fmt::Debug` for `std::vec::Vec<({integer}, itertools::Group<'_, {integer}, std::slice::Iter<'_, ({integer}, {integer})>, [closure@src/main.rs:7:38: 7:45]>)>`
  = note: required by `std::fmt::Debug::fmt`

error: aborting due to previous error

For more information about this error, try `rustc --explain E0277`.
error: Could not compile `playground`.

To learn more, run the command again with --verbose.

You can try this:

let gs: Vec<_> = group.into_iter().flat_map(|(_,a)| a.into_iter()).collect();

It will produce:

[(1, 0), (1, 5), (8, 2), (9, 0)]
1 Like

Thanks, got me on the right track. Your solution just turns it back into the original vec, but changing it to:
let gs: Vec<_> = group.into_iter().map(|(_,a)| a.into_iter().collect::<Vec<_>>()).collect::<Vec<_>>();
returns the desired vec of elements grouped by first tuple field into vecs:
[[(1, 0), (1, 5)], [(8, 2)], [(9, 0)]]