我正在尝试使用 HashMap<String, &Trait>
但是我有一个错误消息我没有't understand. Here'的代码(playpen):
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);
}
这是我得到的错误:
<anon>:14:36: 14:37 error: `s` does not live long enough
<anon>:14 map.insert("key".to_string(), &s);
^
<anon>:12:59: 15:2 note: reference must be valid for the block suffix following statement 0 at 12:58...
<anon>:12 let mut map: HashMap<String, &Trait> = HashMap::new();
<anon>:13 let s = Struct;
<anon>:14 map.insert("key".to_string(), &s);
<anon>:15 }
<anon>:13:20: 15:2 note: ...but borrowed value is only valid for the block suffix following statement 1 at 13:19
<anon>:13 let s = Struct;
<anon>:14 map.insert("key".to_string(), &s);
<anon>:15 }
error: aborting due to previous error
任何人都可以解释这里发生了什么,并建议一个解决方法?
1 回答
map
outlivess
,所以在map
生命中的某个时刻(就在破坏之前),s
将无效 . 这可以通过改变它们的构造顺序来解决,从而解决这个问题:如果您希望
HashMap
拥有引用,请使用拥有的指针: