News for hackers. Stuff that matters.
Re:Using enums to represent state in Rust by zozbot234 on Friday September 22, 2023 @11:03AM (#37612980)
You can do this by just implementing From<u8> and Into<u8> for your type - using the enum representation only for assignment or pattern matching. The more principled solution AIUI would be to have "patterns" as a first-class citizen within the language.

Storing the tag 'out of band' is something you can only do as part of some larger object, in which case you can similarly have getters and setters that take or return enums and do the appropriate conversion.

Re:Using enums to represent state in Rust by brigadier132 on Friday September 22, 2023 @12:01PM (#37613738)
> From<u8> and Into<u8> for your type

It gets verbose fast when you are talking about all combinations of variants of an enum.

Re:Using enums to represent state in Rust by zozbot234 on Friday September 22, 2023 @12:21PM (#37613996)
The point is that you only have to do it once, when defining the object. Everything else then happens via the From and Into implementations, which the compiler will generally be smart enough to inline. So it'll be just as efficient as working on the underlying u8.
Re:Using enums to represent state in Rust by brigadier132 on Friday September 22, 2023 @12:35PM (#37614182)
You have to do it once for each subset of variants your state machine requires. Which if you enumerate them all is 2^N from implementations.
Re:Using enums to represent state in Rust by hurril on Friday September 22, 2023 @12:19PM (#37613975)
Then what does this mean?

let x: u8 = E::Rest(0).into();

let y: E = x.into();

Re:Using enums to represent state in Rust by duped on Friday September 22, 2023 @12:24PM (#37614054)
Bad example, that should panic (in a perfect world it should be a compile error). The invariant of the type is that `E::Rest` cannot hold zero.
Re:Using enums to represent state in Rust by hurril on Friday September 22, 2023 @12:32PM (#37614147)
Why is that a bad example? It's proof that implementing From does not solve the problem.
Re:Using enums to represent state in Rust by duped on Friday September 22, 2023 @12:20PM (#37613979)
That's not equivalent. Notably if you have a `&[u8]` you can't transmute it to `&[E]`. It's also noisy when you have the enum as part of a larger struct, and can make encoding/decoding very verbose.