如何在Vec <box <_>&gt;中为对象添加生命周期自己拥有?

时间:2017-10-16 19:17:45

标签: rust

如何让World拥有system并且他们的生命周期相似的编译器清楚明白?

trait System {
    fn process(&self);
}

struct Action {
    who: i32,
}
impl System for Action {
    fn process(&self) {
        println!("id: {}", self.who);
    }
}

type SystemVec = Vec<Box<System>>;
struct World {
    systems: SystemVec,
}
impl World {
    fn new() -> Self {
        World {
            systems: Vec::new(),
        }
    }

    fn add_system<S: System>(&mut self, system: S) {
        self.systems.push(Box::new(system));
    }
}

fn main() {
    let mut w = World::new();
    w.add_system(Action { who: 0 });
}
error[E0310]: the parameter type `S` may not live long enough
  --> src/main.rs:26:27
   |
26 |         self.systems.push(Box::new(system));
   |                           ^^^^^^^^^^^^^^^^
   |
   = help: consider adding an explicit lifetime bound `S: 'static`...
note: ...so that the type `S` will meet its required lifetime bounds
  --> src/main.rs:26:27
   |
26 |         self.systems.push(Box::new(system));
   |                           ^^^^^^^^^^^^^^^^

0 个答案:

没有答案