本页尚未翻译,以下为英文原文。
#E0106: value used after its lock was released
The value came out of a Mutex or RwLock, and the using block that held the lock has ended, so the lock no longer protects it. Use it inside the using block, or take a copy with .clone().
let m = Mutex::new([1, 2, 3]);
let xs = using g = m.lock() { g.get() };
xs.push(4);
error[E0106]: the value of `g`'s `using` block is what the `Mutex` protects, and the block releases the lock before it is used --> main.nabi:2:10 | 2 | let xs = using g = m.lock() { g.get() }; | ^^^^^ | ------- taken out of the lock here | = help: use it inside the `using` block, or make the block's value `g.get_clone()`
Take a deep copy out of the block with get_clone():
let m = Mutex::new([1, 2, 3]);
let xs = using g = m.lock() { g.get_clone() };
xs.push(4);
println(f"{xs.len()}");
4
The value can leave the block in any form: a loop's break value, a labelled block, an if or match arm, a catch, or a closure's result. Each one is E0106, and the fix is the same.
What a lock guard's get() returns is a view of the protected value: passing it to a function that keeps it is E0106 too.
Related: E0105 value used after it was handed over, E0065 lock guard not released by using, E0136 thread-local value kept past with
Found a mistake? Edit this page on GitHub. Last updated