3

I have a function that returns a HashMap<String, u64> and I want to extend another HashMap<String, u64> with the return value of that function:

pub fn find_album(&self, artist: String, album: String) -> Vec<String>
pub fn get_tracks(&self, album_id: String) -> HashMap<String, u64>
let mut track_nums: HashMap<String, u64> = HashMap::new();
for id in client.find_album(artist, album) {
    track_nums.extend(client.get_tracks(id).iter());
}

This gives me an error:

    error[E0271]: type mismatch resolving `<std::collections::hash_map::Iter<'_, std::string::String, u64> as std::iter::IntoIterator>::Item == (std::string::String, u64)`
  --> src/main.rs:23:20
   |
23 |         track_nums.extend(client.get_tracks(id).iter());
   |                    ^^^^^^ expected reference, found struct `std::string::String`
   |
   = note: expected type `(&std::string::String, &u64)`
          found type `(std::string::String, u64)`

What's the correct way to extend a HashMap with all of the (key, value) pairs from another HashMap?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
user693861
  • 339
  • 3
  • 15
  • 1
    Does `client.get_tracks(id).into_iter()` work? – Tim Diekmann Jun 01 '18 at 00:32
  • 2
    The [`extend`](https://doc.rust-lang.org/std/iter/trait.Extend.html#tymethod.extend) method, which is from the `Extend` trait, takes anything that implements `IntoIterator` -- and `HashMap` does. So `track_nums.extend(client.get_tracks(id))` should work without the `.iter()`. – trent Jun 01 '18 at 00:54
  • `into_iter` worked, thanks! There's a good explanation of `into_iter` here for future reference: https://stackoverflow.com/questions/34733811/what-is-the-difference-between-iter-and-into-iter – user693861 Jun 01 '18 at 00:56
  • @trentcl, that worked too. Thanks! – user693861 Jun 01 '18 at 00:57

0 Answers0