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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With