HashMap 键的寿命不够长

HashMap key does not live long enough

我正在尝试使用 HashMap<String, &Trait>,但我收到一条我不理解的错误消息。这是代码 (playground):

use std::collections::HashMap;

trait Trait {}

struct Struct;

impl Trait for Struct {}

fn main() {
    let mut map: HashMap<String, &Trait> = HashMap::new();
    let s = Struct;
    map.insert("key".to_string(), &s);
}

这是我遇到的错误:

error[E0597]: `s` does not live long enough
  --> src/main.rs:12:36
   |
12 |     map.insert("key".to_string(), &s);
   |                                    ^ borrowed value does not live long enough
13 | }
   | - `s` dropped here while still borrowed
   |
   = note: values in a scope are dropped in the opposite order they are created

这里发生了什么?有解决方法吗?

此问题已通过 non-lexical lifetimes 解决,从 Rust 2018 开始不应成为问题。下面的答案与使用旧版本 Rust 的人相关。


maps长寿,所以在map生命的某个时刻(就在毁灭之前),s将失效。这可以通过改变它们的构造顺序来解决,从而改变破坏顺序:

let s = Struct;
let mut map: HashMap<String, &Trait> = HashMap::new();
map.insert("key".to_string(), &s);

如果您希望 HashMap 拥有引用,请使用拥有的指针:

let mut map: HashMap<String, Box<Trait>> = HashMap::new();
let s = Struct;
map.insert("key".to_string(), Box::new(s));