Why is this MutexGuard not dropped?

The temporaries are cleaned up at the end of the statement, not the end of the expression.

In this case the whole while block is the statement, not just the expression inside the let pattern matching.


Michael's answer is basically correct. More details can be found in Rust's reference regarding Place Expressions, Value Expressions and Temporary Lifetimes:

In the first example (let job = ...), the MutexGuard is a temporary. The temporary lifetime ends at the end of the statement. Therefore the MutexGuard is dropped after the let job = ... statement.

In the second example while let ..., the MutexGuard is part of the scrutinee of the while-expression. This makes the MutexGuard part of a value-expression in a place-expression context. Since promotion to a 'static can't occur, the lifetime of the entire scrutinee is the enclosing block, not the enclosing statement. That is, the MutexGuard is held for the whole while let-block.

Tags:

Lifetime

Rust