Introduction
The map
function in Rust is a powerful and commonly used function that allows you to transform elements of an iterator by applying a closure or function to each element. This function is a part of the Iterator trait and is essential for performing functional programming tasks in Rust.
Syntax
The basic syntax of the map
function is as follows:
iterator.map(|x| { /* transformation logic */ })
The map
function takes a closure as an argument, which defines how each element of the iterator should be transformed. The closure receives each element and returns the transformed value.
Example Usage
Example 1: Incrementing Each Element by 1
fn main() {
let numbers = vec![1, 2, 3, 4, 5];
let incremented: Vec<i32> = numbers.iter().map(|&x| x + 1).collect();
println!("{:?}", incremented);
}
// Output: [2, 3, 4, 5, 6]
Example 2: Converting Strings to Uppercase
fn main() {
let words = vec!["hello", "world"];
let uppercased: Vec<String> = words.iter().map(|&s| s.to_uppercase()).collect();
println!("{:?}", uppercased);
}
// Output: ["HELLO", "WORLD"]
Example 3: Extracting the Length of Each String
fn main() {
let words = vec!["apple", "banana", "cherry"];
let lengths: Vec<usize> = words.iter().map(|&s| s.len()).collect();
println!("{:?}", lengths);
}
// Output: [5, 6, 6]
Example 4: Squaring Each Number
fn main() {
let numbers = vec![1, 2, 3, 4];
let squared: Vec<i32> = numbers.iter().map(|&x| x * x).collect();
println!("{:?}", squared);
}
// Output: [1, 4, 9, 16]
Example 5: Converting an Option to Its Contained Value
fn main() {
let numbers: Vec<Option<i32>> = vec![Some(1), None, Some(3)];
let unwrapped: Vec<i32> = numbers.iter().filter_map(|&x| x).collect();
println!("{:?}", unwrapped);
}
// Output: [1, 3]
See Also
- filter - Filters elements of an iterator based on a predicate.
- collect - Transforms an iterator into a collection.
- fold - Reduces an iterator to a single value by repeatedly applying a function.
- for_each - Applies a function to each element of an iterator for its side effects.
- filter_map - Combines
filter
andmap
to transform and filter elements in one step.