什么时候闭包在没有move关键字的情况下获得其环境的所有权?

时间:2017-06-06 12:44:12

标签: rust

error[E0373]: closure may outlive the current function, but it borrows `x`, which is owned by the current function
  --> <anon>:12:19
   |
12 |     thread::spawn(|| { foo1(x); });
   |                   ^^        - `x` is borrowed here
   |                   |
   |                   may outlive borrowed value `x`
   |
help: to force the closure to take ownership of `x` (and any other referenced variables), use the `move` keyword, as shown:
   |     thread::spawn(move || { foo1(x); });

Playground

错误:

test1

为什么x中的关闭不取代x: i32的所有权,foo1move的签名(x)指定? (我知道我可以添加test2以使其正常工作。)我想这是因为var myParser = { instr: document.getElementById("pString"), v1: [], crstr: function() { return this.instr.value; }, aV: function() { for(i=0;i<this.instr.lenght;i++) { if(this.instr[i] == '(') this.v1.push(0); } return this.v1; } } 是可复制的,但如果它被复制到闭包中那么为什么我仍然有生命周期问题?

然而function pSubmit() { document.write(myParser.crstr() + '</br>'); document.write(myParser.aV()); } 有效。

1 个答案:

答案 0 :(得分:4)

因为 没有取得所有权。移动比简单地借用更具破坏性,因此如果编译器认为它可以通过不移动捕获的值而逃脱,那么它就不会。它会移动String,因为它没有其他选项。它借用i32,因为它是Copy

  

不能躲避不借用它!

Aah,但编译器不知道 它使用的启发式就是:并不总是正确的。

  

难道不能正常运作吗?

可能,但没有人教它如何。

相关问题