在Rust中,迭代一个HashMap
并将结果收集到一个Vec
的可选方法是什么?这是我目前的尝试:
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();
}
抛出错误。
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
to_string()
将&str
转换为String
,因为它会经过整个std::fmt
机器。如果可以从上下文中推断出目标类型是String
,则应使用into()
,否则使用to_owned()
。 - Vladimir Matveev