Caballero
Caballero

Reputation: 12111

Create a vector from iterating hashmap

What is the optional way in Rust to iterate a HashMap and collect the result into a Vec? This is my attempt so far:

use std::collections::HashMap;

struct User {
    reference: String,
    email: String
}

fn main() {

    let mut users: HashMap<String, User> = HashMap::new();
    users.insert("first".to_string(), User { reference: "ref1".to_string(), email: "test@test.com".to_string() });
    users.insert("second".to_string(), User { reference: "ref2".to_string(), email: "test1@test.com".to_string() });
    users.insert("third".to_string(), User { reference: "ref3".to_string(), email: "test3@test.com".to_string() });

    //this is my failed attempt
    let user_refs: Vec<String> = users.iter().map(|(_, user)| &user.reference.clone()).collect();

}

throws an error

src/main.rs:15:85: 15:94 error: the trait `core::iter::FromIterator<&collections::string::String>` is not implemented for the type `collections::vec::Vec<collections::string::String>` [E0277]
src/main.rs:15  let user_refs: Vec<String> = users.iter().map(|(_, user)| &user.reference.clone()).collect();
                                                                                                   ^~~~~~~~~
src/main.rs:15:85: 15:94 note: a collection of type `collections::vec::Vec<collections::string::String>` cannot be built from an iterator over elements of type `&collections::string::String`
src/main.rs:15  let user_refs: Vec<String> = users.iter().map(|(_, user)| &user.reference.clone()).collect();
                                                                                                   ^~~~~~~~~
error: aborting due to previous error

Upvotes: 8

Views: 8722

Answers (1)

llogiq
llogiq

Reputation: 14541

Your resulting Vec needs to own the Strings, so remove the & before the user.reference.clone().

Playground URL: https://play.rust-lang.org/?gist=6a6b50ebf589fcce1dbf&version=nightly

Gist URL: https://gist.github.com/6a6b50ebf589fcce1dbf

Upvotes: 8

Related Questions