【发布时间】:2019-08-05 00:32:03
【问题描述】:
我有一个trait Surface: 'static,我想为struct Obj<'a> 实现它。该特征需要为'static,因为我想将Surface 类型的对象存储在Vec<Box<Surface>> 中。
在第一步中我尝试了这个。
impl<'a> Surface for Obj<'a> {}
由于'static 和'a 之间的生命周期不匹配,这将不起作用。换句话说:Surface 可以比Obj 寿命更长,因为Surface 是'static。
我改变了我的实现如下。
impl<'a> Surface for Obj<'a> where 'a: 'static {}
据我正确理解文档,我正在做的是,'a 可以比'static 寿命长。我想要这个吗?
如果我转移Obj<'a> 的所有权,编译器会告诉我Obj 内部的可变引用将无法生存,并且仍然被借用。
这是一个简短的例子。
trait Surface: 'static {}
struct Manager {
storage: Vec<Box<Surface>>,
}
impl Manager {
fn add(&mut self, surface: impl Surface) {
self.storage.push(Box::new(surface));
}
}
struct SomeOtherStruct {}
struct Obj<'a> {
data: &'a mut SomeOtherStruct,
}
impl<'a> Obj<'a> {
fn new(some_struct: &'a mut SomeOtherStruct) -> Self {
Obj { data: some_struct }
}
}
impl<'a> Surface for Obj<'a> where 'a: 'static {}
fn main() {
let mut some_struct = SomeOtherStruct {};
let mut manager = Manager {
storage: Vec::new(),
};
let obj = Obj::new(&mut some_struct);
manager.add(obj);
}
error[E0597]: `some_struct` does not live long enough
--> src/main.rs:33:24
|
33 | let obj = Obj::new(&mut some_struct);
| ---------^^^^^^^^^^^^^^^^-
| | |
| | borrowed value does not live long enough
| argument requires that `some_struct` is borrowed for `'static`
34 | manager.add(obj);
35 | }
| - `some_struct` dropped here while still borrowed
换句话说&mut some_struct 是生命周期'a 但需要'static。好的很清楚,因为some_struct 住在Obj<'a> 所以它不能是'static?
这就是我想要做的“Rust like”吗?我不知道如何让它工作。它真的与生命相混淆。我想我可以通过使用Rc<T> 来解决这个问题,但这会使事情变得更复杂。
【问题讨论】: