Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

rust
map
iterator
functional
programming

Map function in Rust

Educative Answers Team

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 the into_iter() function.

svg viewer

Syntax

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.

svg viewer

Code

The following examples show how the map function is used.

  • The .iter() and .into_iter() functions are being used to convert a vector into an iterable.
  • The .collect() method consumes the iterator and collects the resulting values into a collection data type.

Example 1

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 22.

Example 2

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);
}
}

RELATED TAGS

rust
map
iterator
functional
programming
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring