我正在尝试闭包:

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

有帮助吗?

解决方案

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

这意味着你会写 || closure() 代替 closure:您正在传递一个新的闭包,该闭包调用您的第一个闭包。

其他提示

(更新:不要这样做,在不久的将来可能会被禁止。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);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top