3 ms·
I'm not very familiar with C++ closures, but I agree with rust closures having room for improvement for a different reason. Lack of fine grained control over co
by gpm 8y ago
I'm not very familiar with C++ closures, but I agree with rust closures having room for improvement for a different reason. Lack of fine grained control over copy/move.
let settings = thing_it_wants_to_take_by_reference;
let channel = thing_it_needs_to_take_ownership_of;
let closure_that_takes_everything_by_reference =
|| { some_code(settings, channel) };
let closure_that_takes_everything_by_move =
move || { some_code(settings, channel) };
let closure_that_does_what_I_want = {
let ref_settings = &settings;
move || { some_code(ref_settings, channel) }
};
let closure_with_hypothetical_syntax =
|| [move channel] { some_code(settings, channel) };
- steveklabnik 8y agoThis was a fairly explicit design decision, because these cases come up so rarely. It's our opinion that it's not common enough to be worth increasing the complexity of the language. You don't even need it in this case; this will compile, for example: fn main() { let settings = String::new(); let channel = String::new(); let closure_with_hypothetical_syntax = || { some_code(&settings, channel) }; } fn some_code(settings: &String, channel: String) { } The only difference is the & on settings in the closure. This moves channel but not settings.
- gpm 8y agoWait... hmm... now I'm going to have to track down some code where I did this trick and figure out why or if I was just being stupid.
- steveklabnik 8y agoIt’s cool! In general, the default is “rust tries to capture each thing the way it needs to be” and you can use move to override that. Sometimes, you do have to do what you wrote, at least in theory. I’ve never actually had to.
- chrismorgan 8y agoIf your closures need to be 'static, it’s common in my experience to need to use `move`, and thus to need to clone types like Rc<T>. It depends on whether you’re dealing with Fn, FnMut or FnOnce, too.
- RReverser 8y agoHmm, your examples seem to show pretty fine grained control over moves / borrows?
- int_19h 8y agoNote that the last one (which is the only one that has explicit fine-grained - i.e. per-variable - control) is marked "hypothetical".
- steveklabnik 8y agoIt’s special syntax for the thing before it. You can still do exactly that in rust today, it’s just more verbose.