【发布时间】:2019-12-30 03:08:53
【问题描述】:
我有两个具有相同键的HashMap<&str, String>,我希望创建一个具有相同键的HashMap,其中组合了值。我不想保留对前两个HashMaps 的引用,但想将Strings 移动到新的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
【问题讨论】: