fra*_*nza 5 rust borrow-checker
我正在尝试使用HashMap<String, &Trait>但我有一个我不明白的错误信息.这是代码(围栏):
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);
}
Run Code Online (Sandbox Code Playgroud)
这是我得到的错误:
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
Run Code Online (Sandbox Code Playgroud)
任何人都可以解释这里发生了什么,并建议一个解决方法?
map会超越s,所以在某些时候map的生活(只是破坏之前),s将是无效的.这可以通过改变它们的构造顺序来解决,从而解决这个问题:
let s = Struct;
let mut map: HashMap<String, &Trait> = HashMap::new();
map.insert("key".to_string(), &s);
Run Code Online (Sandbox Code Playgroud)
如果您想要HashMap拥有引用,请使用拥有的指针:
let mut map: HashMap<String, Box<Trait>> = HashMap::new();
let s = Struct;
map.insert("key".to_string(), Box::new(s));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
524 次 |
| 最近记录: |