Login
You're viewing the ruby.social public feed.
  • Nov 15, 2026, 12:25 PM

    There seems to be some idea out there that state machines would be hard in #Rust.

    From my expetience, it is pretty much the opposite:
    With the decent mix of thread safety with functional and OO style features, such as encapsulating state in struct instances, it is pretty easy, but you need to understand it once, of course.

    TL;DR keep an *internal* Arc<Mutex<T>> around and use it in methods - that gains you tons of capabilities.
    Do operations and handle your state transforms in one place.

    💬 1🔄 0⭐ 0

Replies

  • Nov 15, 2026, 12:38 PM

    @CyReVolt swapping the state can be a bit of a pain with strict ownership rules. Like you may want to match on the previous state and then in the match statement take ownership of the previous state, modify it and put it back. This fails in multiple ways. I always end up adding a “Poisoned” variant to my state enum, make it the default and then std::mem::take the state before matching/modifying it.

    💬 0🔄 0⭐ 0
  • Nov 16, 2026, 5:37 AM

    @CyReVolt that’s even over complicating it. I often model state machines as enums with consuming (no mut self) methods for transitions. And for whatever greater struct that this is a part of, using a similar pattern of returning a new struct with just one field changed works well. Compilers are smart so this is efficient. And I find the pattern greatly enhances robustness since there are no mut edit surprises possible :)

    💬 1🔄 0⭐ 0
  • 💬 0🔄 0⭐ 0