我有两个相同键的HashMap<&str, String>
,我希望创建一个具有相同键但值组合在一起的HashMap
。我不想保留对第一个和第二个HashMap
的引用,而是想将String
移动到新的HashMap
中。
use std::collections::HashMap;
#[derive(Debug)]
struct Contact {
phone: String,
address: String,
}
fn main() {
let mut phones: HashMap<&str, String> = HashMap::new();
phones.insert("Daniel", "798-1364".into());
phones.insert("Ashley", "645-7689".into());
phones.insert("Katie", "435-8291".into());
phones.insert("Robert", "956-1745".into());
let mut addresses: HashMap<&str, String> = HashMap::new();
addresses.insert("Daniel", "12 A Street".into());
addresses.insert("Ashley", "12 B Street".into());
addresses.insert("Katie", "12 C Street".into());
addresses.insert("Robert", "12 D Street".into());
let contacts: HashMap<&str, Contact> = phones.keys().fold(HashMap::new(), |mut acc, value| {
acc.entry(value).or_insert(Contact {
phone: *phones.get(value).unwrap(),
address: *addresses.get(value).unwrap(),
});
acc
});
println!("{:?}", contacts);
}
但是我遇到了一个错误。
error[E0507]: cannot move out of a shared reference
--> src/main.rs:24:20
|
24 | phone: *phones.get(value).unwrap(),
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^ move occurs because value has type `std::string::String`, which does not implement the `Copy` trait
error[E0507]: cannot move out of a shared reference
--> src/main.rs:25:22
|
25 | address: *addresses.get(value).unwrap(),
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ move occurs because value has type `std::string::String`, which does not implement the `Copy` trait
flat_map
版本。 - Shepmasterflat_map
,它会简单地跳过它们。 - trent