4 ms·
This got me wondering what I actually do in practice. I think it's this: const KnownFlavors { Vanilla: "Vanilla", Chocolate: "Chocolate", Strawb
by jasonkester 2y ago
This got me wondering what I actually do in practice. I think it's this:
const KnownFlavors {
Vanilla: "Vanilla",
Chocolate: "Chocolate",
Strawberry: "Strawberry"
}
Then, use a string to hold the actual value.
doug.favoriteFlavor = KnownFlavors.Chocolate;
cindy.favoriteFlavor = "Mint"
case: KnownFlavors.Chocolate:
Expand your list of known flavors whenever you like, your system will still always hold valid data. You get all the benefits of typo-proofing your code, switching on an enum, etc., without having to pile on any wackiness to fool your compiler or keep the data normalized.
It acknowledges the reality that a non-exhaustive enum isn’t really an enum. It’s just a list of things that people might type into that field.
- Boldened15 2y agoSorry I don't get the example, are both code blocks meant to be client-side code? > It acknowledges the reality that a non-exhaustive enum isn’t really an enum. It’s just a list of things that people might type into that field. I would say the opposite, the kinds of enums that map a case to a few hardcoded branches (SUCCESS, NETWORK_ERROR, API_ERROR) are often an approximation of algebraic data types which Rust implements as enums [0] but not most languages or data formats. Since often using those will require something like a `nullthrows($response->getNetworkError())` once you've matched the enum case. The kind of enum that's just a string whitelist, like flavors or colors, which you can freely pass around and store, likely converting it into a human-readable string or RGB values in one or two utils, is the classic kind of enum to me. [0] https://doc.rust-lang.org/std/keyword.enum.html https://doc.rust-lang.org/std/keyword.enum.html
- PartiallyTyped 2y agoThe way we do this with AWS SDK in rust is by leveraging #non_exhaustive, and matching the (_@other) pattern, this is forward compatible and allows us to do something like ( _@other) if other.name() == “foo” for known cases without upgrading down the road or if the user uses an older version than our API.