簡體   English   中英

通過一個關閉兩次沒有它移開

[英]Passing a closure twice without it getting moved away

我正在嘗試閉包:

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()而不是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 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM