I made some traits to make it easy to create state machines. I have really enjoyed using it, and wanted feedback. Is there anything that can be improved? Would you find this useful for creating state machines?
note: The context field can be used for many different things. I have used it for the publish queue of a publish/subscribe framework. I think it could also be useful for giving read only access to a parent state machine which would handle certain base events.
The issue I see with this approach is poor(er) performance due to dynamic dispatch. I was thinking about writing a macro that generates state machines without traits based on some dot-like syntax, just in order to avoid that issue.
I needed to use a state machine once before and ended up writing out every state as a struct and then the code that was using it required exact states to operate on. I can't think of any use cases for projects I'm working on that would require a trait for states right now, but I'm sure they do exist.
That sounds interesting. If it wouldn't use dynamic dispatch, how would it control the state it is executing? A match statement on a set of states? Do you have an example of writing out every state as a struct?
No, discrete functions. Here's an example with rendering which only has 1 transition.
I just remembered also writing one to replace a regex expr because we required the regex crate for only a single statement in the whole codebase. But that one used numbers for state and used a loop.
But yeah, the rendering example is not something I would be comfortable handing over to a library to manage I think. The transitions are static and in main. It's a poor example because of the small number of transitions, but there's codebases doing similar things with 4/5 states and several transitions, all of which are (for the most part) static.
Transitions, outside of formalisms, can also have side effects, so returning just the next state isn't enough for some cases - one of my projects (discrete event simulation) in fact exploits something like that: atomic state machines are connected together through a separate layer (event I/O) and communicate together.