1

I have a simple structure with a lifetime parameter:

struct Exit<'a> { from: &'a Location<'a>, to: &'a Location<'a> }

And another structure that contains them in a Vec:

struct Location<'a> { exits: Vec<Exit<'a>> }

I can add new Exits to Locations:

let mut start = Location { exits: Vec::with_capacity(4) };
let mut end = Location { exits: Vec::with_capacity(4) };
start.exits.push(Exit { from: &start, to: &end, name: String::from("North")});

But I'd like to make a function to do this, and that's where I'm running into problems with lifetimes:

impl <'a> Location<'a> {
    fn add_exit(& mut self, target: &'a Location<'a>, exit_name: String) {
        self.exits.push(Exit { from: self, to: target, name: exit_name });
    }
}

The lifetime of the Exit only exists in the function, so I get a "cannot infer an appropriate lifetime for lifetime parameter 'a due to conflicting requirements" error.

I was hoping naievely that by pushing the Exit into the Vec it would take ownership of the structure and extend the lifetime.

How can I achieve what I want here?

Andy
  • 3,596
  • 8
  • 34
  • 33

0 Answers0