0

How do I go about making it clear to the compiler that World will own system and that their lifetimes are similar?

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));
   |                           ^^^^^^^^^^^^^^^^
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
tamato
  • 838
  • 7
  • 15
  • Did you do as the compiler suggests: *consider adding an explicit lifetime bound `S: 'static` so that the type `S` will meet its required lifetime bounds*? – Shepmaster Oct 16 '17 at 19:27
  • yes, and I tried adding a lifetype, couldn't find a way to add it. And just 'S: 'static` doesn't help me in actually adding it. – tamato Oct 16 '17 at 19:35
  • *doesn't help me in actually adding it* — [seems to work for me](https://play.rust-lang.org/?gist=3890cb86f1c1ee0e15165609a25a3503&version=stable). – Shepmaster Oct 16 '17 at 19:38
  • What you have in your link *does* help. Part of my problem is not knowing the synatx – tamato Oct 16 '17 at 19:39
  • Seriously, I encourage you to file an issue (or find an existing one) at the [Rust repository](https://github.com/rust-lang/rust). Rust always wants to make error messages better — if this wasn't clear enough, it can probably be improved. – Shepmaster Oct 16 '17 at 19:46

0 Answers0