3

我正在尝试关闭:

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);
                           ^~~~~~~

编译器实际上就如何解决问题提出了建议,但我还没有找到成功应用它的方法。

有什么建议么?:D

4

2 回答 2

2

注意:`closure` 移到这里是因为它的类型为 `||`,这是一个不可复制的堆栈闭包(在新闭包中捕获它,例如 `|x| f(x)`,以覆盖)

这意味着您将编写|| closure()而不是closure: 您正在传入一个调用您的第一个闭包的新闭包。

于 2014-02-25T05:53:17.747 回答
0

(更新:不要这样做,它可能在不久的将来被禁止。A&mut ||现在和将来可能会正常工作。请参阅此答案的评论中的讨论和链接。)

另一种潜在的方法(虽然有点难读):

fn call_it(f_ref: &||) { // now takes a borrowed reference to a closure
    (*f_ref)();
}
let klosure = || println("closure!");
call_it(&klosure);
call_it(&klosure);
于 2014-02-26T11:15:11.813 回答