Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a vector from iterating hashmap

Tags:

rust

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: "[email protected]".to_string() });
    users.insert("second".to_string(), User { reference: "ref2".to_string(), email: "[email protected]".to_string() });
    users.insert("third".to_string(), User { reference: "ref3".to_string(), email: "[email protected]".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
like image 400
Caballero Avatar asked Jun 19 '15 08:06

Caballero


1 Answers

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

like image 99
llogiq Avatar answered Oct 07 '22 18:10

llogiq