Day 13h: Vector Transformation and Functional Programming Techniques
Introduction
Rust supports powerful functional programming techniques when working with vectors. In this session, we’ll explore transformations using map()
, filter()
, and more. We'll also look at chaining multiple iterator methods to achieve complex operations.
Transforming Vectors with map()
The map()
method applies a function to each element in the vector, transforming it into a new vector. Here’s how it works:
fn main() {
let numbers = vec![1, 2, 3, 4];
let squares: Vec<i32> = numbers.iter().map(|&x| x * x).collect();
println!("{:?}", squares); // Output: [1, 4, 9, 16]
}
Filtering Elements with filter()
The filter()
method allows you to retain only the elements that satisfy a condition.
fn main() {
let numbers = vec![1, 2, 3, 4, 5, 6];
let evens: Vec<i32> = numbers.into_iter().filter(|&x| x % 2 == 0).collect();
println!("{:?}", evens); // Output: [2, 4, 6]
}
Chaining Iterators
You can chain multiple iterator methods together for more complex transformations. This is both efficient and expressive.
fn main() {
let numbers = vec![1, 2, 3, 4, 5, 6];
let result: Vec<i32> = numbers
.into_iter()
.filter(|&x| x % 2 == 0)
.map(|x| x * x)
.collect();
println!("{:?}", result); // Output: [4, 16, 36]
}
Conclusion
Functional programming techniques like map()
and filter()
provide a clean and efficient way to transform vectors in Rust. Chaining iterators allows you to perform complex transformations in a concise manner.