这是一个极为简化的例子,我的问题是:给定一个实现了
Ord
的 trait Thing
和一个实现了 Thing
的 struct Object
,我有以下结构体:pub struct MyStruct<'a> {
my_things: HashMap<i32, Vec<Box<dyn Thing + 'a>>>
}
impl<'a> MyStruct<'a> {
pub fn new() -> MyStruct<'a> {
MyStruct {
my_things: HashMap::new()
}
}
pub fn add_object(&mut self, key: i32, obj: Object) {
if !self.my_things.contains_key(&key) {
self.my_things.insert(key, Vec::new());
}
let new_thing: Box<dyn Thing> = Box::new(obj);
let things = self.my_things.get_mut(&key).unwrap();
things.push(new_thing);
things.sort();
}
}
这个函数接受一个键和一个Object
,并使用给定的键将对象添加到Vec
的HashMap
中。我知道这不是最优的方法,但为了说明问题,我想保持简单。
在调用things.sort()
时,编译器报错,错误如下:
error[E0308]: mismatched types
--> src/main.rs:58:16
|
58 | things.sort();
| ^^^^ lifetime mismatch
|
= note: expected trait `Ord`
found trait `Ord`
note: the lifetime `'a` as defined on the impl at 42:6...
--> src/main.rs:42:6
|
42 | impl<'a> MyStruct<'a> {
| ^^
= note: ...does not necessarily outlive the static lifetime
如果我在这个例子中移除所有的 'a
生命周期,那么代码将会编译通过。但是对于我的实际使用情况,我需要允许非静态生命周期。
有人能解释一下发生了什么吗?sort()
真的需要 Vec
包含具有静态生命周期的项吗? 如果是这样,为什么?
有好的解决方法吗?