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.
let (even, odd): (Vec<i32>, Vec<i32>) = (1..=6).partition(|n| n % 2 == 0); // even = [2, 4, 6], odd = [1, 3, 5]
Try it
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.
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
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,HashSetorString, so writelet (a, b): (Vec<_>, Vec<_>) = .... - Single pass. Compared with two
filtercalls it evaluates the predicate once per item and works on iterators you can only traverse once. - Predicate gets
&Item. Withiter()over integers that is&&i32, hence patterns like|&&a| a >= 18;into_iter()orcopied()makes it&i32. - Only two groups. For more than two groups, use
foldwith aHashMap, orchunk_byon slices after sorting. - Result handling:
partition(Result::is_ok)keepsResultwrappers and needs an unwrap step afterwards. If you want to stop at the first error instead,collect::<Result<Vec<_>, _>>()is the right tool; seecollect. partition_in_place(slices, nightly) reorders a slice in place and is not available on stable.unzipof larger tuples is not provided; nest pairs (((a, b), c)) or use several passes.- Complexity: O(n) time and memory for the output collections.
Related
collect,enumerate and zip,map and filter,HashSet- Lessons: Iterators, Iterator patterns