rust - Create a vector from iterating hashmap -
what optional way in rust iterate hashmap , collect result vec? attempt 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 failed attempt let user_refs: vec<string> = users.iter().map(|(_, user)| &user.reference.clone()).collect(); } throws error
src/main.rs:15:85: 15:94 error: trait `core::iter::fromiterator<&collections::string::string>` not implemented 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: collection of type `collections::vec::vec<collections::string::string>` cannot built iterator on 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 previous error
your resulting vec needs own strings, remove & before user.reference.clone().
playground url: https://play.rust-lang.org/?gist=6a6b50ebf589fcce1dbf&version=nightly
Comments
Post a Comment