Rust Lifetime Error But Not Understand How to Resolve It

Hello everyone:

I met an error when my code compiled. It says:

error[E0597]: `e` does not live long enough

Here is my code on the playground.

I understand the literal meaning of the error. I think it caused because the variable e is dropped out of the for loop. But sadly, I don't know how to resolve it.

Thanks for any comment!

This is kind of the culprit. Given your definition of MinPQ, that pq vec will have to contain &'a &'a Edge. Note how we have a:

  • nested borrow,

  • with the same lifetime name / parameter for the outer borrow and the inner borrow.

This is overconstraining (basically once you borrow some long-lived object, that very borrow then needs storage that is as much long-lived as the initial borrowee, so that the borrow itself can then be borrowed that long. In practice, this is almost never possible (it's exactly the problem you hit with e in your for loop: itself is borrowing something for a long-lived lifetime ('a, of the edges), but the e itself is short-lived). Nested borrows with identical lifetime is thus an anti-pattern / a mistake that needs to be avoided.

  • In your case, the main question is why does PQ use &'a T as its element type: since it is generic, you can use T as the element type, and then pick T = &'a Edge.

  • The other option is to define the pq field as:

    -   pq: MinPQ<'a, &'a Edge>, // 横切边(包括失效的边)
    +   pq: MinPQ<'a,     Edge>, // 横切边(包括失效的边)

so as not to have &'a &'a Edge but just &'a Edge: Playground


Your answer really helped me a lot, thank you very much!

I understand now. As you saied, the nested borrow I defined to pq is not what I want.

1 Like