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
答案 0 :(得分:4)
您生成的Vec需要拥有字符串,因此请在&
之前删除user.reference.clone()
。
游乐场网址:https://play.rust-lang.org/?gist=6a6b50ebf589fcce1dbf&version=nightly