Why do I get “does not live long enough” in a return value?

As pointed out in Stargateur’s answer, the reason for this is the lifetime of temporaries. While Rust does not have a full specification yet, the language reference still is quite good and at least gives a hint to understand the behaviour. Here is the relevant part from the section about temporary lifetimes:

[T]he lifetime of temporary values is typically

  • the innermost enclosing statement; the tail expression of a block is considered part of the statement that encloses the block, or
  • the condition expression or the loop conditional expression if the temporary is created in the condition expression of an if or in the loop conditional expression of a while expression.

The innermost enclosing statement of body.lock().unwrap() in the second version of your function is the return expression. The spec above states that this expression is “considered part of the statement that encloses the block”, which doesn’t really exist in this case, but it still gives the right idea: All variables local to the function body are dropped before any temporaries in the return expression is dropped, so body is dropped before the MutexGuard that borrows body. The fix you found makes sure the temporary is dropped before body, since local variables are dropped roughly in reverse order of their creation.

Leave a Comment