Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

As someone not versed in Rust I understand the point of the article is showing the Enum construct is powerful, but if you are worried about self-documenting code and want to avoid illegal state transitions, isn't it as simple as defining a map of (pseudocode here):

    {Active -> Inactive,
     Inactive -> Active,
     Active -> Suspended,
     Suspended -> Active,
     ...}
And then having only _one_ function that mutates and checks for the valid transitions? In the author's implementation you need to read a lot of code to derive the state machine from the method's implementations instead of it being immediately obvious from looking at a data structure. I understand there's a benefit of the implementation being checked by the compiler in this way, but at the same time it seem to spread logic across many methods. Is there an alternative middle-ground?


Agreed. I've actually been criticized at several positions for a big "manage_transition" function that is basically either chained if statements or a switch. Either is fine as long as you keep it linear and organized. Both can be terrible if you don't do those things. But, most alternatives can get unwieldy for the same reasons.

The worst is when someone refactors it into a "modern" approach and then proceeds to break the general flow of the state machine again and again.


To me this feels similar to C++ where you have to choose between static or dynamic dispatch at the implementation (template vs virtual methods). This means the user is forced into it one or the other.

While in Rust, the implementation is done for a Trait, and the user can choose static or dynamic dispatch (Trait vs dyn Trait).

I feel the same dissonance between static and dynamic state machines in Rust (type states vs enum). Sometimes I want to enforce it at compile time, while sometimes, at runtime. And the implementation is forced to choose for the user.

I am sure one could write some (proc) macro, and there might be some crates to do that already. But it doesn't feel as elegant as the static/dynamic Trait in my mind.


How is that checked at compile time?




Consider applying for YC's Fall 2025 batch! Applications are open till Aug 4

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: