Closing twice without moving it

I am experimenting with closing:

fn call_it(f: ||) {
    f(); 
}
let klosure = || println("closure!");
call_it(klosure);
call_it(klosure); //Blows up here

Passing cllosure to call_it () twice causes a compiler error due to moving the closure value:

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

The compiler does make a suggestion on how to solve the problem, but I did not understand how to successfully apply it.

Any suggestions ?: D

+3
source share
2 answers

note: `closure` moved here because it has type` || `, which is a stack close, not copyable (grab it in a new close, for example` | x | f (x)`, to override)

This means that you should write || closure()instead closure: you pass in a new closure that causes your first closure.

+2
source

(: , . &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);
0

All Articles