我正在尝试使用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
这里发生了什么?有没有解决方法?
map
比s
存活更久吗?我以为变量在作用域结束时被销毁,所以有特定的销毁顺序吗? - franzalet x = 1; let y = T(&x);
,y
的解构器可能需要访问x
。 - Veedrac