cre*_*lem 5 traits lifetime rust
我有一个trait Surface: 'static我想为 a 实现的struct Obj<'a>。该特征需要是'static因为我想将类型的对象存储Surface在 a 中Vec<Box<Surface>>。
第一步我尝试了这个。
impl<'a> Surface for Obj<'a> {}
Run Code Online (Sandbox Code Playgroud)
这不会起作用,因为'static和之间的生命周期不匹配'a。换句话说:可以比现在Surface活得更久。我改变了我的实现如下。ObjSurface'static
impl<'a> Surface for Obj<'a> where 'a: 'static {}
Run Code Online (Sandbox Code Playgroud)
据我正确理解文档,我正在做的是,'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);
}
Run Code Online (Sandbox Code Playgroud)
(游乐场)
impl<'a> Surface for Obj<'a> {}
Run Code Online (Sandbox Code Playgroud)
换句话说&mut some_struct就是一生'a不过需要'static。好吧,很清楚,因为some_struct住在里面,Obj<'a>所以不可能吗'static?
这就是我想做的“像铁锈一样”吗?我不知道如何让它发挥作用。这真的让人很困惑。我想我可以通过使用 a 来解决这个问题Rc<T>,但这会让事情变得更加复杂。
如何
'static为具有生命周期的结构实现具有生命周期的特征'a?
你不这样做,也不可能。生命周期的目的'static是说“在程序的整个持续时间内都存在的东西”。除了其自身之外,没有任意生命周期'a满足此要求。 'static