What I want to do is:
let mut a = HashMap::<String, Option<&str>>::new();
let s = "123".to_string();
let v = Some(&s[..]);
a.insert(s, v); // won't work
// let entry = a.raw_entry_mut().from_key(&s).or_insert(s, v); // won't work
for (k, v) in a.iter_mut() { // this works, but I'll need to find the entry after insertion
*v = Some(&k);
}
That is, I want to have a map with Value holding a reference to it's key. However the code refuses to compile:
error[E0505]: cannot move out of `s` because it is borrowed
--> src/main.rs:9:14
|
8 | let v = Some(&s[..]);
| - borrow of `s` occurs here
9 | a.insert(s, v);
| ^ - borrow later used here
| |
| move out of `s` occurs here
For more information about this error, try `rustc --explain E0505`.
There is a workaround, but requires cloning the String:
let id = "123".to_string();
HashMap::from([
(id.clone(), Some(id)),
]);