HashMap initialization via ::new vs collect


Learning Rust via "The Rust Programming Language (Covers Rust 2018)" by Carol Nichols and I'm working through the chapter on collections. I've run into a behavior I don't understand, which isn't highlighted in the book. Given the code

    let mut scores = HashMap::new();   
    scores.insert(String::from("Yellow"), 50);
    let uscore = scores.entry(String::from("Blue")).or_insert(0);

    // Populating a HashMap via zip and collect
    let teams = vec![String::from("Blue"),String::from("Red")];
    let initial_scores = vec![10,30];

    let mut scorezip: HashMap<_,_> = teams.iter().zip(initial_scores.iter()).collect();
    let nscore = scorezip.entry(&String::from("Blue")).or_insert(&0);

I don't understand why in the second HashMap, created using collect() over the two vectors, that the entries are stored via reference, where the first example there is no need to include the reference. I suspect it's something to do with how zip creates tuples which are then collected into a map, but don't really understand how.



1 Like

The iter() method iterates by reference, so that's what you ended up collecting. You can iterate values with teams.into_iter().zip(initial_scores.into_iter()).

Note also that zip takes an IntoIterator type, so you can leave that conversion implicit. That is, zip(vec.iter()) is the same as zip(&vec), and zip(vec.into_iter()) is the same as zip(vec).


I understand now - thanks for the answer!

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.