rust - rust 生命周期参数必须超过静态生命周期

标签 rust static traits lifetime

因此,我遵循this tutorial构建类似流氓的行为,并决定开始使用specs调度程序来简化系统的注册和执行。

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


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内。

关于rust - rust 生命周期参数必须超过静态生命周期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59880262/

相关文章:

Android:杀死每个 Activity 是否相当于销毁整个应用程序?

PHP 5.4 - 特性和 self /静态

generics - Rust 泛型 : Expected <T> found <Foo>

rust - 如何固定 crate 的间接依赖项?

rust - 如何获得rust-sdl2窗口表面并同时使用事件迭代器?

java - 为什么我不能在主类中创建除 main 方法之外的另一个方法?

c# - 静态类的静态方法如何知道调用者?

rust - 如何在成员方法闭包中使用struct self

windows - 无法在 Windows 中运行系统命令

generics - 如何安全地存储通用值的不可变别名副本?