5 ms·
Just looking at the example, I notice that you have to use Enums to pass messages around. E.g. "IncrementPressed" in the example. Wouldn't it be much easier to
by amelius 5y ago
Just looking at the example, I notice that you have to use Enums to pass messages around. E.g. "IncrementPressed" in the example. Wouldn't it be much easier to use closures for that? Managing Enums sounds like an unnecessary administrative burden.
- Dowwie 5y agoEnums are a natural fit for event handling. If you write an api that can manage 50 different kinds of events, a single enum consisting of 50 variants would be able to facilitate that. A closure isn't identifiable to the request handler. It's just a thing that does stuff, when you're ready to call it. How do you know what stuff to do with it?
- amelius 5y agoWhat I mean is: binding an enum to an action, which then sends a message containing the enum, deciphering it and executing code based on its value, and not forgetting to define the enum somewhere, when ... you could simply bind the closure to the action. So instead of: Button::new(&mut self.increment_button, Text::new("+")) .on_press(Message::IncrementPressed) you would write: Button::new(&mut self.increment_button, Text::new("+")) .on_press(|| MY_CODE_HERE) For comparison, in JavaScript you can write: button.onclick = function(){ ++counter; } That's quite a direct way of formulating what you want to happen. All in a single line and no Enums involved.
- WJW 5y agoThe enum of all possible events is still there, it's just spread over dozens of different callback properties belonging to several different objects. Splitting out via an enum to a big `handle` type function makes it possible to detect whether you have handled all possible events at compile time instead of having to raise an exception at runtime.
- jbverschoor 5y agoJust require a callback to be non-null.
- varajelle 5y agoI see little value in seeing that enum of all possible event on one place. On the other hand, I want to see what is the action performed by that button and there is value in having small event handler close to the thing they handle.
- verdagon 5y agoIf we had a closure, we wouldn't ever need to "handle all possible events", we would just do a virtual call. It's guaranteed to be handled.
- nybble41 5y agoThe 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.
- int_19h 5y agoIronic. Desktop UI APIs used to be designed around enums of messages as the primary surface (e.g. Win32), but then UI frameworks wrapped all that to allow us to write code that looks exactly like you suggested. Now it's back to messages again... I wonder when we get back to wrapping them. ~
- jbverschoor 5y agoMessage passing is a lower level construct. It's nice in the way that you can have multiple subscribers, but for __most__ application you won't need it. I mean, we're not really doing this anymore, right? while( (bRet = GetMessage( &msg, NULL, 0, 0 )) != 0) {}
- Narishma 5y agoWhat's wrong with that?
- jerf 5y agoConsider the Enums simply as defunctionalized closures. https://blog.sigplan.org/2019/12/30/defunctionalization-everybody-does-it-nobody-talks-about-it/ https://blog.sigplan.org/2019/12/30/defunctionalization-ever... There are significant advantages to this sort of defunctionalization in a system like this. It is a bit more administratively at the point of enum definition, but the flexibility and simplification of the other parts of the program will be a win for almost any non-trivial UI application, not to mention the future-proofing it gives you.
- amelius 5y agoCould you give a concrete example of the benefits? I prefer to avoid abstract discussion since it might not apply to 99% of my code. And by the way, defunctionalization sounds a lot like transforming my code into a bytecode interpreter which interprets my code. This is something I don't need and which would make my code slower and more difficult to read.
- b3morales 5y agoOne key difference is that the defunctionalized representation is serializable. An example feature that enables is that you can now have a GUI for your interface construction, letting you preview the layout while you build it. The controls are hooked up to the message names, which can be be deserialized at runtime and used for dispatch. Attaching live functions, especially closures, to them is not really feasible.
- amelius 5y agoDo you think that at one point Rust could automatically transform my code into defunctionalized form, and thus make it serializable? What you describe sounds like QT Creator, by the way.
- b3morales 5y ago> Do you think that at one point Rust could automatically transform my code into defunctionalized form, and thus make it serializable? For a pure function some kind of bytecode representation is certainly conceivable, but as soon as you add captures it gets much more complex. > QT Creator Precisely, yup; or Android's Layout Editor/Apple's Interface Builder.
- Skinney 5y agoThere are several benefits to using enums as opposed to closures: 1. All your actions are in one place. Figuring out what can happen as a result of a series of user interactions can be done without navigating through a component hierarchy. 2. The history of a user interaction is simple to serialize. In case of error, you can dump the user interaction history for this session (just a list of enum values, right?) to disk. This can then be submitted in bug reports for easy re-production of an issue. 3. It's simple(r) to create a time-travelling debugger that can move backwards and forwards in time, since it can simply re-play the series of messages to a specific point. 4. Since you've seperated state changes from the UI, writing unit tests that ensures that a series of user interactions results in a specific state is pretty easy. You just send in the enum values representing a specific use interaction then check what state you've ended up with.
- verdagon 5y ago> 1. All your actions are in one place. Figuring out what can happen as a result of a series of user interactions can be done without navigating through a component hierarchy. I'd imagine it would be easier to just call a method on whatever we want to update, instead of lowering all our methods into enums. Why wouldn't we do that instead? Also, serializing usually isn't enough to get the benefits you describe. You need true determinism for that, and that's very difficult to achieve. If you ever e.g. query the current date without recording it you've just introduced nondeterminism. If we could really achieve deterministic replayability easily, then I might be okay with the drawback of turning methods into enums.
- Skinney 5y ago> I'd imagine it would be easier to just call a method on whatever we want to update, instead of lowering all our methods into enums. Why wouldn't we do that instead? Easier how? The difference in lines of code is minimal. It's not going to make any meaningful difference in how much time you spend on crafting a solution. > Also, serializing usually isn't enough to get the benefits you describe. You need true determinism for that, and that's very difficult to achieve. If you ever e.g. query the current date without recording it you've just introduced nondeterminism. It requires some thought, but it isn't terribly difficult. Most user interactions with a gui doesn't require a side effect, and those that do can usually be written in a way that it gets represented in the enum. Even when nondeterminism creeps in, it rarely cancels out all of the benefits of having a history of user interaction. Perfect nedn't be the enemy of good.
- scns 5y agoUsing Enums makes you build a Finite State Machine and therefore all effects/state transitions explicit and concentrated at one place. This enables you to see what this particular piece of code is able to do. Methods could obscure what might happen. Using inline closures would make it hard if not impossible to get an overview what might happen.
- Jweb_Guru 5y agoNo one has addressed the actual issue here, unfortunately. There's a good reason why you'll often find message passing done with enums in Rust where other languages use closures, and it's not ideological. In Rust, if you want to access shared state, you need to hold onto a reference to it. If a reference captured by a closure is unique, the compiler conservatively prevents you from not only accessing that variable, but anything that could transitively lead to it, and if it's shared, the compiler prevents you from mutating anything that could lead to it. Additionally, you can't move or destroy the object until there's no chance any value transitively referenced through it is still borrowed--which across threads, often means pretty much no borrow length will suffice. In a UI framework sending stuff across threads, that's a totally unacceptable state of affairs. By contrast, enums that declaratively specify what you want to modify have no such issues, because the state only needs to be accessed when you actually want to run the event. There are three ways to work around the lifetime part, but they're not ideal. The most common is to use something like Rc or Arc, which allow reference counting (a primitive form of garbage collection). Reference counting always makes your objects shared, so it guarantees you'll have to tackle the mutation problem somehow, which can be unsatisfying; it also has a runtime cost (which can be quite significant) and can cause memory leaks if you have cycles in your data (though this is rarely an issue in UI frameworks). Secondly, you can architect your application around things like arenas, which give you "scoped" access to lifetimes--these can be really efficient with the right use case, especially pointer-spaghetti graphs, but can restrict a lot of the patterns you'd write in Rust, since the arenas have to outlive everything you want to do with the objects. Finally, you can separate your shared data from the closure--which works great but now you are restricted to "bare" functions or functions that only capture unrelated state. The closure can't specify the state it wants to update, it has to be directed to the object--which is much less ideal (since now the closures aren't universal in any way, as they need to be passed in the state they want to modify). You can work around the mutation part in two ways, but neither is that great. One is, again, to ban closures from capturing any environment state, so the data is still stored separately and has to be passed in, which has the limitations mentioned previously. The other is to use "interior mutability" which uses some combination of runtime checks and other restrictions to guarantee that you're only accessing the element one at a time. Almost invariably, these mechanisms are slower at runtime, restrict your types somehow (e.g. making them non thread safe), can cause your program to panic if you misuse them, or are just plain annoying to use (or some combination of all of these). So when you can avoid this option, you do! So basically: enums make a ton of sense in Rust because they totally avoid these borrow checker issues. Your intuitions about using closures for this stuff in functional or garbage collected languages don't apply here--patterns that make a lot of sense in them don't work at all in Rust. That's one big reason there are so many Rust UI frameworks rather than just wrapping the C ones or using the same patterns you see in functional languages--the usual patterns simply don't work well. That's not say there aren't some upsides to the approach from a reasoning standpoint. A big one is that it enforces "single writer" control flow--just one place is responsible for all the state updates, so you don't have to worry about synchronization weirdness due to lots of places updating the state on their own. IME, this helps a lot with reasoning. But not everyone agrees that that outweighs the convenience of being able to use a callback, which I totally get--it's just that the "convenient way" isn't really convenient in Rust at all. And it's this that causes all these libraries to be designed this way (at least that's been my experience), not theoretical concerns about serialization and stuff which I agree is basically a nonissue in practice.