Is it possible to split a vector into groups of 10 using iterators?

I have let myVec = vec![0..25] and I would like to split myVec into iterators of groups of 10:

 [0,1,2,3,4,5,6,7,8,9] [10,11,12,13,14,15,16,17,18,19] [20,21,22,23,24,25,None,None,None,None] 

Is it possible to do this with iterators in Rust?

+5
source share
1 answer

There is no such helper method on Iterator trait directly. However, there are two main ways to do this:

  • Use the [T]::chunks() method (which can be called directly on Vec<T> ), however it has a slight difference: it will not produce None , but the last iteration gives a smaller fragment.

    An example :

     let my_vec = (0..25).collect::<Vec<_>>(); for chunk in my_vec.chunks(10) { println!("{:02?}", chunk); } 

    Result:

     [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] [10, 11, 12, 13, 14, 15, 16, 17, 18, 19] [20, 21, 22, 23, 24] 
  • Use the Itertools::chunks() method from the itertools box . This box extends the Iterator feature from the standard library. So this chunks() method works with all iterators! Please note that use is a little more complicated to be general. This has the same behavior as the method described above: in the last iteration, the chunk will be less than containing None s.

    An example :

     extern crate itertools; use itertools::Itertools; for chunk in &(0..25).chunks(10) { println!("{:02?}", chunk.collect::<Vec<_>>()); } 

    Result:

     [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] [10, 11, 12, 13, 14, 15, 16, 17, 18, 19] [20, 21, 22, 23, 24] 

Also note that:

  • In your code, vec![0..25] does not do what you expect from it! It will create a vector with element one . This item is a Range . I fixed this in the examples above.
  • In Rust, variables are named snake_case .
+7
source

Source: https://habr.com/ru/post/1272796/


All Articles