Explain this code!

fn main() {
    let num_vec = vec![10, 9, 8];

    num_vec
        .iter()
        .enumerate()
        .map(|(index, number)| println!("Index number {} has number {}", index, number));

}

1.how this code works?
2.what happen when calling .iter method
3.what happen when calling .enumarate method
4.what happen when calling .map method

  1. Please check the pinned topic and format your post accordingly.
  2. This code doesn't "work", in that it doesn't do anything when run, as you can see in the playground. Compiler even hints you on the reason why. And by "doesn't do anything" I mean, literally - in release mode it compiles to nothing.
  3. For other questions, see: Vec::iter, Iterator::enumerate, Iterator::map.
5 Likes

But at the top, you didn't save the iterator anywhere, or make it iterate, so it does nothing. You create a lazy, nested iterator and then throw it away. What you probably wanted:

    for (index, number) in num_vec.iter().enumerate() {
        println!("Index number {} has number {}", index, number);
    }

Or

    num_vec.iter().enumerate().for_each(|(index, number)| {
        println!("Index number {} has number {}", index, number);
    });

Both of these consume the iterator and make it iterate over all the values.

3 Likes

Please read the documentation.

2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.