#E0136: 執行緒區域值保留到 with 之後
ThreadLocal 的 with 只在呼叫期間把值借給它的閉包。閉包卻保留了它、回傳了它、移交了它,或帶著它 await,因此它會比呼叫存活得更久,或移到另一個執行緒。在閉包內使用它,改為把 .clone() 或由它算出的結果帶出來。
nabi
use std::thread;
static TL: thread::ThreadLocal<List<i32>> = thread::local(|| -> List<i32> { [1, 2, 3] });
let xs = TL.with(|l| l);
error[E0136]: this returns the value `with` lends out of its closure: the value is only lent to it --> main.nabi:5:22 | 5 | let xs = TL.with(|l| l); | ^ | = help: return a copy (`.clone()`) or what you computed from it, or take a `ThreadLocal`'s value out with `replace` / `take`
回傳一份複本:
nabi
use std::thread;
static TL: thread::ThreadLocal<List<i32>> = thread::local(|| -> List<i32> { [1, 2, 3] });
let xs = TL.with(|l| l.clone());
xs.push(4);
println(f"{xs.len()}");
4
相關錯誤碼:E0106 值在其鎖釋放後被使用、E0105 值在移交後被使用
發現錯誤? 在 GitHub 上編輯此頁 最後更新: