HashMap密钥的活动时间不够长

问题描述 投票:5回答:1

我正在尝试使用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

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

rust borrow-checker
1个回答
9
投票

这个问题是用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));
© www.soinside.com 2019 - 2024. All rights reserved.