5 ms·
The iced package requires the messages to implement the Debug, Clone, and Send traits, none of which are available for closures. I was able to implement somethi
by nybble41 5y ago
The iced package requires the messages to implement the Debug, Clone, and Send traits, none of which are available for closures. I was able to implement something similar to your example[0] but it only supports plain function pointers for the callbacks. The compiler wasn't able to derive a sufficiently general Debug trait for the function pointer due to an issue with the lifetime of the argument, so I had to implement that myself as well.
[Edit: Ignore this next paragraph; as steveklabnik pointed out, this change has already been implemented and "Message(|c| c.value += 1)" is accepted by the latest stable version.] Incidentally, as long as there are situations where only function pointers can be used and not closures it would be really nice to have some support for anonymous function pointers in Rust (with the fn type and not just the Fn trait) so that one could write e.g. "Message(fn |c| c.value += 1)" instead of "Message({ fn f(c: &mut Counter) { c.value += 1 } f })". Or just infer the fn type for "closures" which don't actually close over any variables without the need for an extra keyword.
[0] https://github.com/nybble41/iced-counter2/blob/master/src/main.rs https://github.com/nybble41/iced-counter2/blob/master/src/ma...
- steveklabnik 5y agoI’m not at my computer but I thought non-capturing closures already will coerce into a fn.
- nybble41 5y agoIt seems you're right. That didn't work the last time I tried it—which I admit was some time ago—but it does work in the latest stable version of rustc.
- steveklabnik 5y agoLooks like support was added about four years ago, but it is true this wasn’t the case a whole back. Glad it’s working now though!
- jayd16 5y agoPretty funny to read the arguments about how enums are the one true way and here we see function pointers are already supported.
- Jweb_Guru 5y agoBare function pointers are, but not state-capturing ones (see my other comment for why that is). Without state capture, closures really aren't more ergonomic to use than enums in most cases, and are often less so.