In Ada, if I use an enum (carrying the example from a link I used in a cousin comment):
type Expr_Kind_Type is (Bin_Op_Plus,
Bin_Op_Minus,
Num);
https://learn.adacore.com/courses/intro-to-ada/chapters/more...Variant records using this enum have to implement the variant for each element of the enum. If I, for some reason, have multiple records using the same discriminant I can know that each one implements it for each value of the discriminant. Does Rust have a way to synchronize your enums similar to that?
pub trait Payloads {
type Read;
type Write;
}
pub enum FileOp<P: Payloads> {
Read(P::Read),
Write(P::Write),
}
pub struct Inputs;
impl Payloads for Inputs {
type Read = ();
type Write = u8;
}
pub type Request = FileOp<Inputs>;
pub struct Outputs;
impl Payloads for Outputs {
type Read = u8;
type Write = ();
}
pub type Reply = FileOp<Outputs>;
pub fn execute(request: Request) -> Reply {
match request {
Request::Read(()) => Reply::Read(42),
Request::Write(_) => Reply::Write(()),
}
} pub struct Bare;
impl Payloads for Bare {
type Read = ();
type Write = ();
}
pub type BareFileOp = FileOp<Bare>
Correct? So you'd need to create it with BareFileOp::Read(()), but at least it wouldn't carry any overhead of actually containing data. enum Parser {
bin_add(...),
bin_sub(...),
...
}
enum Typer {
bin_add(...),
bin_sub(...),
...
}
And I'd have to hope they were both complete and match (at least according to what I know now, that's why I'm asking). If I go back in to the Parser enum and add a `un_minus`, then I have to also go into the Typer enum (apologies for the bad naming, I'm at work and commenting between my way too many meetings) and manually add it. I have no compile time guarantee that both are complete and synchronized. In Ada, I modify the existing enum and both will fail to compile until I add in the variant for `un_minus`. One edit, multiple failures distributed across the code base as a result telling me all the places where I have to add in a new code branch or new variant.EDIT: Run on sentence broken up.
I have found it quite useful to be able to generate a dedicated SomeEnumDiscriminants enum for SomeEnum, using the following derive:
https://docs.rs/strum/latest/strum/derive.EnumDiscriminants....
The union type always implies a kind, after all, so it's a generalization of the concept.
https://docs.rs/strum/latest/strum/derive.EnumDiscriminants....