我想构建一个HashMap
结构向量,其中键是结构中的String
字段,值是结构本身。看起来这应该是可能的,无需复制。我想将结构的生命周期移动到HashMap
,然后密钥将具有相同的生命周期,因为只要HashMap
包含结构,它就有效。
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);
}
}
这给了我以下错误
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 }
非常感谢任何帮助整理出来!