生锈寿命参数必须比静态寿命长

rust lifetime parameter must outlive the static lifetime

所以我正在跟随 this tutorial 构建一个 rogue-like 并且我决定开始使用 specs dispatcher 来使注册和执行系统更容易一些。

为此,我在 State 结构中添加了 Dispatcher


use rltk::{GameState, Rltk};
use specs::world::World;
use specs::Dispatcher;


pub struct State<'a, 'b> {  // <-- Added new lifetime params here for dispacher
    pub ecs: World,
    pub dsp: Dispatcher<'a, 'b>,
}

但是当我尝试为其实现 GameSate 特性时,我 运行 遇到了问题:

impl<'a, 'b> GameState for State<'a, 'b> {
    fn tick(&mut self, ctx: &mut Rltk) {
        ctx.cls();
        self.dsp.dispatch(&mut self.ecs);
        self.ecs.maintain();
    }
}

我收到这些错误:

error[E0478]: lifetime bound not satisfied
  --> src/sys/state.rs:96:14
   |
96 | impl<'a, 'b> GameState for State<'a, 'b> {
   |              ^^^^^^^^^
   |
note: lifetime parameter instantiated with the lifetime `'a` as defined on the impl at 96:6
  --> src/sys/state.rs:96:6
   |
96 | impl<'a, 'b> GameState for State<'a, 'b> {
   |      ^^
   = note: but lifetime parameter must outlive the static lifetime

error[E0478]: lifetime bound not satisfied
  --> src/sys/state.rs:96:14
   |
96 | impl<'a, 'b> GameState for State<'a, 'b> {
   |              ^^^^^^^^^
   |
note: lifetime parameter instantiated with the lifetime `'b` as defined on the impl at 96:10
  --> src/sys/state.rs:96:10
   |
96 | impl<'a, 'b> GameState for State<'a, 'b> {
   |          ^^
   = note: but lifetime parameter must outlive the static lifetime

它希望生命周期 'a, 'b'static 长,这听起来不可能,因为我确信 'static 是整个程序的生命周期。

我该如何解决?

GameState要求实现者必须是'static:

pub trait GameState: 'static {...}

为了满足 'static 生命周期,您的类型不得包含任何短于 'static 的引用。所以,如果你不能让 'a'b 都成为 'static,唯一的选择就是不要把 Dispatcher 放在 State.[=21 里面=]