我正在尝试闭包:
fn call_it(f: ||) {
f();
}
let klosure = || println("closure!");
call_it(klosure);
call_it(klosure); //Blows up here将klosure传递到call_it()中两次会导致编译器错误,因为闭包值会被移动:
closures.rs:16:13: 16:20 error: use of moved value: `klosure`
closures.rs:16 call_it(klosure);
^~~~~~~
closures.rs:15:13: 15:20 note: `closure` moved here because it has type `||`, which is a non-copyable stack closure (capture it in a new closure, e.g. `|x| f(x)`, to override)
closures.rs:15 call_it(klosure);
^~~~~~~编译器实际上对如何解决这个问题提出了建议,但我还没有想出一种成功应用它的方法。
有什么建议吗?
发布于 2014-02-25 05:53:17
注意:
closure搬到这里是因为它有||类型,这是一个不可复制的堆栈闭包(在一个新的闭包中捕获它,例如|x| f(x))。
这意味着您将编写|| closure()而不是closure:您正在传递一个新闭包,该闭包调用您的第一个闭包。
https://stackoverflow.com/questions/22005693
复制相似问题