Introduction
The partition
function in Rust is a method provided by the Iterator
trait that allows you to split an iterator into two collections based on a predicate. It returns a tuple of two collections: one containing elements that satisfy the predicate and another containing elements that do not. This function is useful for categorizing or filtering data.
Syntax
The basic syntax of the partition
function is as follows:
iterator.partition(|item| {
// predicate logic
})
Here, iterator
is any type that implements the Iterator
trait, and |item|
is a closure that defines the predicate to be tested against each element.
Example Usage
Example 1: Partitioning Even and Odd Numbers
fn main() {
let numbers = vec![1, 2, 3, 4, 5, 6];
let (even, odd): (Vec<i32>, Vec<i32>) = numbers.into_iter().partition(|&x| x % 2 == 0);
println!("Even: {:?}, Odd: {:?}", even, odd);
// Output: Even: [2, 4, 6], Odd: [1, 3, 5]
}
Example 2: Partitioning Characters
fn main() {
let chars = vec!['a', '1', 'b', '2', 'c', '3'];
let (letters, digits): (Vec<char>, Vec<char>) = chars.into_iter().partition(|c| c.is_alphabetic());
println!("Letters: {:?}, Digits: {:?}", letters, digits);
// Output: Letters: ['a', 'b', 'c'], Digits: ['1', '2', '3']
}
Example 3: Partitioning Based on String Length
fn main() {
let words = vec!["short", "longer", "tiny", "lengthy"];
let (short, long): (Vec<&str>, Vec<&str>) = words.into_iter().partition(|&word| word.len() <= 5);
println!("Short: {:?}, Long: {:?}", short, long);
// Output: Short: ["short", "tiny"], Long: ["longer", "lengthy"]
}
Example 4: Partitioning Numbers into Positive and Negative
fn main() {
let numbers = vec![-1, 2, -3, 4, -5, 6];
let (positive, negative): (Vec<i32>, Vec<i32>) = numbers.into_iter().partition(|&x| x > 0);
println!("Positive: {:?}, Negative: {:?}", positive, negative);
// Output: Positive: [2, 4, 6], Negative: [-1, -3, -5]
}
Example 5: Partitioning Based on Custom Struct Field
struct Person {
name: String,
age: u32,
}
fn main() {
let people = vec![
Person { name: "Alice".to_string(), age: 30 },
Person { name: "Bob".to_string(), age: 20 },
Person { name: "Charlie".to_string(), age: 25 },
];
let (adults, minors): (Vec<Person>, Vec<Person>) = people.into_iter().partition(|p| p.age >= 21);
println!("Adults: {:?}, Minors: {:?}", adults, minors);
// Output: Adults: [Person { name: "Alice", age: 30 }, Person { name: "Charlie", age: 25 }], Minors: [Person { name: "Bob", age: 20 }]
}