【问题标题】:HashMap key does not live long enoughHashMap 键的寿命不够长
【发布时间】:2015-08-24 00:00:09
【问题描述】:

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

    此问题已通过 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));
    

    【讨论】:

    • 谢谢,这行得通。但是你能解释一下为什么maps 更长寿吗?我以为变量在作用域结束时就被销毁了,那么有没有具体的销毁顺序呢?
    • "有没有具体的销毁顺序" → 与构造顺序相反,因为如果你有let x = 1; let y = T(&amp;x);y的析构函数可能需要访问x。跨度>
    • 哦,我明白了。我认为这是因为这些变量是在堆栈中分配的。
    猜你喜欢
    • 2015-05-26
    • 1970-01-01
    • 2020-12-17
    • 1970-01-01
    • 2015-02-28
    • 1970-01-01
    • 1970-01-01
    • 2019-04-03
    • 2017-03-09
    相关资源
    最近更新 更多