The Map()
method applies a function to each element in an iterable and returns the resulting iterable, of each iteration, to the next function.
Note: The Iterator type in Rust is used to perform much of the functional heavy-lifting. Any Vec of elements can be transformed into an Iterator using either the
iter()
or theinto_iter()
function.
The map()
can only be applied to iterables. Therefore, to apply the map()
function to a vector, we need to first convert it to an iterable.
The following examples show how the map function is used.
.iter()
and .into_iter()
functions are being used to convert a vector into an iterable..collect()
method consumes the iterator and collects the resulting values into a collection data type.fn main() {let vector = [1, 2, 3];let result = vector.iter().map(|x| x * 2).collect::<Vec<i32>>();// another way to write the above statement/*let result: Vec<i32> = vector.iter().map(|x| x * 2).collect();*/println!("After mapping: {:?}", result);}
The above code takes each item in the list and multiplies it by .
fn main() {let mut count = 0;for pair in vec!['a', 'b', 'c'].into_iter().map(|single_letter| { count += 1; (single_letter, count) }){println!("{:?}", pair);}}