I ask this question as a dev coming from Typescript, where something like this is possible when defining a type, and is particularly useful for discriminated unions:
enum ColorFormat {
Hex,
RGB,
}
type Color =
| {
format: ColorFormat.Hex, // <-- value is being used as a type here
value: string,
}
| {
format: ColorFormat.RGB,
r: number,
b: number,
g: number,
};
Trying to do something like this in rust might look super similar:
enum ColorFormat {
Hex,
RGB,
}
enum Color {
Hex {
format: "hex", // <-- static string
value: String,
},
RGB {
format: ColorFormat::RGB, // <-- static usize (i think?) in this context
r: u8,
b: u8,
g: u8,
},
}
Of course, in the rust case, the format
tag isn't exactly valuable because that information can be garnered by checking the enum variant itself. But, in my particular use case, I'm defining an enum for data that comes back from an API, and it'd be neat if I could specify the actual value of the discriminator field for each variant, rather than a broad String or numeric type.
EDIT:
Sorry, should have specified, I'm already using Serde for de/serialization purposes. What I'm interested in is having the type safety that comes with the compiler knowing in-advance what the value of something is. Not necessarily to this contrived example, but more broadly.