存储在Struct中的引用的生存时间不够长,无法关闭



我在另一个Struct中持有对一个Struct的引用,这两个Struc都在同一块中声明。稍后我想在一个重复运行且从不返回的闭包中使用外部Struct。Struct内部的引用显然存在时间不够长,但在我看来,它永远不应该超出范围,或者至少应该与它所指的Struct一样长:

struct MyStruct;
struct ReferenceStruct<'a> {
reference: &'a MyStruct
}
impl<'a> ReferenceStruct<'a> {
fn do_something(&self) -> () {}
}
fn run<F>(mut function: F) -> !
where
F: FnMut() -> () + 'static
{
loop {
function();
}
}
fn main() {
let my_struct = MyStruct;
let reference = ReferenceStruct { reference: &my_struct };
run(move || {
reference.do_something();
});
}

(链接到操场(

run函数(用于上下文(镜像了一个事件循环,类似于Winit的事件循环。实际上,我有另一个Struct,它拥有被引用的值,但本例用较少的行再现它。

错误:

error[E0597]: `my_struct` does not live long enough
--> srcmain.rs:26:50
|
26 |       let reference = ReferenceStruct { reference: &my_struct };
|                                                    ^^^^^^^^^^ borrowed value does not live long enough
27 | 
28 | /     run(move ||
29 | |     {
30 | |         reference.do_something();
31 | |     });
| |______- argument requires that `my_struct` is borrowed for `'static`
32 |   }
|   - `my_struct` dropped here while still borrowed

my_struct似乎被丢弃在main的末尾,但即使程序流以某种方式逃脱了循环,它也肯定会持续引用结构的长度,这是它需要的长度。我不知道这个错误是从哪里或如何产生的,也不知道该怎么办。

您的问题是传递到run()的闭包的生存期绑定'static。这意味着reference的生存期也是'static,因为它被移动到闭包中,这反过来意味着my_struct也必须具有静态生存期——事实并非如此。

幸运的是,您不需要在此绑定'static。如果你去掉它,一切都会正常工作:

...
fn run<F>(mut function: F) -> !
where
F: FnMut() -> ()
...

但是,如果事件循环需要闭包为'static,那么在您的用例中,这可能不是一个解决方案。

最新更新