3

I'm experimenting with closures:

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

Passing klosure into call_it() twice causes a compiler error on account of the closure value getting moved:

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 actually makes a suggestion on how to resolve the issue, but I've not figured out a way to successfully apply it.

Any suggestions? :D

Greg Malcolm
  • 3,238
  • 4
  • 23
  • 24

2 Answers2

2

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)

This means that you would write || closure() instead of closure: you are passing in a new closure which calls your first closure.

Chris Morgan
  • 86,207
  • 24
  • 208
  • 215
0

(Update: Don't do this, it might be disallowed in the near future. A &mut || will probably work just fine now and in the future. See discussion and links in the comments on this answer.)

Another potential approach (though a bit uglier to read):

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);
pnkfelix
  • 3,770
  • 29
  • 45
  • Isn't it incorrect to call a closure through a `&` (for the same reason it's incorrect to mutate a `& &mut T`)? E.g. it allows one to [recreate "the case of the recurring closure"](https://gist.github.com/huonw/a2134c85f1ecf2c9ef04). (I talked to Niko about it, he referred me to [#12224](https://github.com/mozilla/rust/issues/12224).) – huon Feb 27 '14 at 04:06
  • Ah yes you are probably right. For on-lookers, the original "case of the recurring closure" is http://smallcultfollowing.com/babysteps/blog/2013/04/30/the-case-of-the-recurring-closure/ – pnkfelix Feb 27 '14 at 11:05