I want to build a HashMap
of a vector of structures where the key is a String
field in the structure and the value is the structure itself. It seems like this should be possible without copying. I want to move the lifetime of the structure to the HashMap
and then the key would have the same lifetime since it's valid as long as the HashMap
contains the structure.
use std::collections::{HashMap};
#[derive(Hash, PartialEq, Eq)]
struct A {
pub x: String,
}
fn main() {
let mut map = HashMap::new();
let mut vec = Vec::new();
vec.push(A { x: "foo".to_string() });
for x in vec {
map.insert(&x.x, x);
}
}
This gives me the following error
src/main.rs:13:19: 13:22 error: `x.x` does not live long enough
src/main.rs:13 map.insert(&x.x, x);
^~~
src/main.rs:9:34: 15:2 note: reference must be valid for the block suffix following statement 0 at 9:33...
src/main.rs: 9 let mut map = HashMap::new();
src/main.rs:10 let mut vec = Vec::new();
src/main.rs:11 vec.push(A { x: "foo".to_string() });
src/main.rs:12 for x in vec {
src/main.rs:13 map.insert(&x.x, x);
src/main.rs:14 }
...
src/main.rs:12:5: 14:6 note: ...but borrowed value is only valid for the for at 12:4
src/main.rs:12 for x in vec {
src/main.rs:13 map.insert(&x.x, x);
src/main.rs:14 }
Any help sorting this out is greatly appreciated!