Argument requires that borrow lasts for `'a`

Hello, i have a vector which holds all existing units.
There is a second vector for the selected units.
Each unit have a roadmap (vector of point2).

struct Unit {
    rect: Rect,
    vel: Vector,
    hovered: bool,
    enemy: bool,
    selected: bool,
    roadmap: Vec<Point2<f32>>,

impl Unit {    

    fn new(x: f32, y: f32, enemybool: bool) -> Self {
        Unit {
            rect: Rect::new(x,y, unit_W, unit_H),
            vel: Vector { x: 0.0, y: 0.0 },
            hovered: false,
            enemy: enemybool,
            selected: false,
            roadmap: Vec::new(),

struct MainState<'a, 'b> {    

    vecUnit: Vec<&'a mut Unit>,
    vecSelectedUnit: Vec<&'b mut Unit>,

impl<'a, 'b> EventHandler for MainState<'a, 'b> {
    fn update(&mut self, ctx: &mut ggez::Context) -> ggez::GameResult {
	if self.vecUnit.len() == 0 {
		    self.vecUnit.push(&mut Unit::new(10.0,700.0, false))
		    self.vecUnit.push(Unit::new(110.0,700.0, true));		    

i get error:
impl<'a, 'b> EventHandler for MainState<'a, 'b> {
| -- lifetime 'a defined here
472 | self.vecUnit.push(&mut Unit::new(10.0,700.0, false))
| -----------------------^^^^^^^^^^^^^^^^^^^^^^^^^^^^-
| | |
| | creates a temporary which is freed while still in use
| argument requires that borrow lasts for 'a
483 | }
| - temporary value is freed at the end of this statement

are my lifetimes wrong ?
should i reimplement push ?

Your MainState declared as a temporary view into another struct, and is unable to store any data by itself. It's probably not what you want.

Rust references are not generally usable for referencing objects longer than for a duration of a single function call. They are unsuitable for what other languages mean by "storing by reference". They are for borrowing objects temporarily and preventing them from being moved.

Do not use references inside structs. Use owned types or owned shared references like Arc.

thank you kornel

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.