存储在 Struct 中的引用的寿命不足以关闭

Reference stored in Struct does not live long enough for closure

我在另一个 Struct 中持有对一个 Struct 的引用,这两个 Struct 都在同一个块中声明。 我后来想在一个闭包中使用外部结构,它是 运行 重复而不是 returns。 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();
    });
}

(link to playground)

运行 函数(针对上下文)反映了一个事件循环,类似于 Winit 的事件循环,实际上,我有另一个 Struct,它拥有的值为已引用,但此示例用更少的行重现了它。

错误:

error[E0597]: `my_struct` does not live long enough
  --> src\main.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 的末尾,但即使程序流以某种方式逃脱了循环,它肯定会持续与 reference 结构一样长的时间,这是它需要的时间。我不明白这个错误可能在哪里或如何发生,或者如何处理它。

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

幸运的是,您不需要在此处绑定 'static。如果删除它,一切正常:

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

但是,如果事件循环需要闭包 'static

,这可能不是您用例中的解决方案