Closure in map, printing a vector

hello I am trying to print a vec using map:

mod sort;

use std::io::{self, Write};

fn main() {

    //let i: i32 = -5;
    //println!("{}", i as usize);

    let mut a: Vec<i32> = vec![1, 2, 3];
    let k = *a.iter().max().unwrap() + 1;
    sort::mod_count_sort(&mut a, k);

    a.iter().map(|x| println!("{}", *x));

}

And vector never gets printed.

Maps are lazy, meaning that they are only computed when they are actually used.
The more appropriate method of printing that out would be putting println statement in a for-loop that iterates over a (The vec)
In this example, I print out the contents of the vec, and in this other example, I collect the map, meaning that it iterates through every possible item that the map could produce and puts them into a Vec<i32>. This runs the |x| {println!("{}", *x); *x} statement and therefore the items that the map outputs are actually calculated (In this example, the “calculation” actually prints them and returns the value).

1 Like

Be sure to pay attention to the warnings you’re getting:

warning: unused `std::iter::Map` which must be used
 --> src/main.rs:4:5
  |
4 |     a.iter().map(|x| println!("{}", *x));
  |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  |
  = note: #[warn(unused_must_use)] on by default
  = note: iterator adaptors are lazy and do nothing unless consumed

You might want Iterator::for_each.

3 Likes