0

Take the following code snippet:

use std::collections::HashMap;

fn main() {
    let mut en_fr_map: HashMap<String, String> = HashMap::new();
    en_fr_map.insert(String::from("Hello"), String::from("Bonjour"));
    en_fr_map.insert(String::from("World"), String::from("Monde"));

    for (key, value) in en_fr_map {
        println!("key is {} and value is {}", key, value);
    }
}

Which compiles fines and spits out the following output:

key is Hello and value is Bonjour
key is World and value is Monde

Now, if I change the for loop to this:

for (key, value) in en_fr_map.iter() {
    println!("key is {} and value is {}", key, value);
}

That is, calling the iter() function on the map, the result is the same. How are they different?

Paul Razvan Berg
  • 16,949
  • 9
  • 76
  • 114
  • https://doc.rust-lang.org/rust-by-example/trait/iter.html – Stargateur Mar 15 '20 at 15:50
  • 2
    A `for` loop implicitly calls `into_iter()` on the value passed to it. See also [What is the difference between iter and into_iter?](https://stackoverflow.com/q/34733811/7246614) – timotree Mar 15 '20 at 15:50
  • Does this answer your question? [What is the difference between iter and into\_iter?](https://stackoverflow.com/questions/34733811/what-is-the-difference-between-iter-and-into-iter) – timotree Mar 15 '20 at 15:53
  • 1
    Yes @timotree. Your clarification that a for loop implicitly calls `into_iter()` was particularly helpful. – Paul Razvan Berg Mar 15 '20 at 15:56

0 Answers0