Link Menu Search Expand Document

Rust

Table of contents

  1. map

map

Creates a lazy iterator. Does not execute the function in the map until the iterator is actually consumed.

fn main() {
  let a = [1,2,3];
  a.iter().map(|n| println!("n*2 = {}", n * 2));
}

This doesn’t do anything unless the iterator is consumed.

fn main() {
  let a = [1,2,3];
  let mut b = a.iter().map(|n| println!("n*2 = {}", n * 2));

  while b.next() != None {};

}

This one executes the functions that were maped.

My understanding is that if you want to perform some action over a list, your best option is to use a for loop.

Quoting the documentation:

map() is conceptually similar to a for loop. However, as map() is lazy, it is
best used when you're already working with other iterators. If you're doing
some sort of looping for a side effect, it's considered more idiomatic to use
for than map().

So this is probably how it should look like:

fn main() {
  let a = [1,2,3];
  for n in a.iter() {
    println!("n * 2 = {}", n * 2);
  }
}

A non-idiomatic way can also look like this:

fn main() {
  let a = [1,2,3];
  let b: Vec<()> = a.iter().map(|n| println!("n*2 = {}", n * 2)).collect();

}

Weird thing about this is that you have to provide a type to the variable. Even if you are not going to use the result (by using let _ instead of a named variable) you still need to provide the type as the compiler can’t infer it.


Gilgalab Knowledge Base