3 ms·
My favorite rust state-machine-ism is consuming self by value when you transition. In combination with generics and From, this allows you to ensure that states
by __jem 6y ago
My favorite rust state-machine-ism is consuming self by value when you transition. In combination with generics and From, this allows you to ensure that states are only ever entered into via the transitions you encode by implementing the trait, and because the previous state is totally consumed it makes the transitions super clear.
- monocasa 6y agoI started off by doing that, but ultimately didn't like it for my use cases. * It didn't seem to grant a lot of benefits over pattern matching (errors were pushed to compile time checks in both cases). * It had larger cognitive overhead since the allowed transitions were either all over the place in the source instead of in one match statement or weren't colocated with their structs. * It didn't seem nearly as good at attacking the combinatorial complexity you see in these matrices as pattern matching is.
- __jem 6y agoIt's definitely not a great fit if you have a ton of different state transitions, since the From impls add a lot of boiler plate. But I've found it perfect for situations where there's only a few very well defined transitions, like the Raft implementation suggested in the blog post I linked in parent reply.
- deleted 6y ago[deleted]
- pdimitar 6y agoI'd love to read a blog post detailing exactly how is this done.
- tangjurine 6y agoCould you explain a little more? That sounds really cool.
- __jem 6y agoHere's a good blog on the topic: https://hoverbear.org/blog/rust-state-machine-pattern/ https://hoverbear.org/blog/rust-state-machine-pattern/. The last implementation of Raft uses this pattern.