Skip to content
Tutorials Center
My learning

Topics

Rust Reference ยท Iterators

Iterator partition, unzip and collect into pairs

Reference for splitting a Rust iterator into two collections: partition by a predicate, unzip pairs into two vectors, and Result partitioning idioms.

partition splits one iterator into two collections in a single pass: items for which a predicate is true go to the first, the rest to the second. unzip is for iterators of pairs: it splits (A, B) items into a collection of As and a collection of Bs.

Both are consumers, and both build their results with Default + Extend, so the target can be a Vec, a HashSet, a String or any other collection that supports extending.

Rust
let (even, odd): (Vec<i32>, Vec<i32>) = (1..=6).partition(|n| n % 2 == 0);
// even = [2, 4, 6], odd = [1, 3, 5]

Try it

Rust partition by a rule

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Rust unzip into two collections

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Syntax

Rust
fn partition<B, F>(self, f: F) -> (B, B)
    where B: Default + Extend<Self::Item>, F: FnMut(&Self::Item) -> bool;

fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB)
    where Self: Iterator<Item = (A, B)>,
          FromA: Default + Extend<A>,
          FromB: Default + Extend<B>;
Name Description
f Predicate that receives a reference to each item; true sends the item to the first collection.
B, FromA, FromB Target collection types. Usually written as a type annotation on the result tuple.

Returns: a tuple of two collections. partition returns two collections of the same type; unzip may use different types for each half.

Errors / panics / edge cases: no panics beyond what the collections do (allocation failure). The relative order of items within each side is preserved. An empty iterator gives two empty collections.

Usage notes

  • A type annotation is required. Rust cannot guess whether you want Vec, HashSet or String, so write let (a, b): (Vec<_>, Vec<_>) = ....
  • Single pass. Compared with two filter calls it evaluates the predicate once per item and works on iterators you can only traverse once.
  • Predicate gets &Item. With iter() over integers that is &&i32, hence patterns like |&&a| a >= 18; into_iter() or copied() makes it &i32.
  • Only two groups. For more than two groups, use fold with a HashMap, or chunk_by on slices after sorting.
  • Result handling: partition(Result::is_ok) keeps Result wrappers and needs an unwrap step afterwards. If you want to stop at the first error instead, collect::<Result<Vec<_>, _>>() is the right tool; see collect.
  • partition_in_place (slices, nightly) reorders a slice in place and is not available on stable.
  • unzip of larger tuples is not provided; nest pairs (((a, b), c)) or use several passes.
  • Complexity: O(n) time and memory for the output collections.