rustlifetimeborrow

Mutable reference to Vec<_> does not live long enough in while loop


Here's the code so far, the relevant lines are 27 and 28: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=37bba701ad2e9d47741da1149881ddd1

Error message:

error[E0597]: `neighs` does not live long enough
  --> src/lib.rs:28:25
   |
17 |     while let Some(Reverse(current)) = open.pop() {
   |                                        ---------- borrow later used here
...
28 |         for neighbor in neighs.iter_mut() {
   |                         ^^^^^^^^^^^^^^^^^ borrowed value does not live long enough
...
38 |     }
   |     - `neighs` dropped here while still borrowed

I used Rust a few times in the past, and I'm fully aware of how basic this problem should be. I've also spent hours trying different things and googling similar problems. I just can't seem to find a solution. How do I make neighs live as long as function a_star?


Solution

  • I would suggest:

    1. Store copies of Cell in open instead of references to Cell
    open.push(Reverse(start.clone()));
    
    
    1. Make the parent field of the Cell struct a Box or Rc instead of reference:
    #[derive(Clone, Eq)]
    pub struct Cell {
        coords: (u32, u32),
        g_cost: u32,
        h_cost: u32,
        parent: Option<std::rc::Rc<Cell>>,
    }
    

    This way open will not reference any of neighs elements or current. which will avoid lifetime issues.