docs

#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 上编辑此页 最后更新: