logoalt Hacker News

Jtsummers • yesterday at 10:47 PM • 2 replies • view on HN

As someone who hasn't used Rust enough, and not knowing Zig but it appears Zig does something similar to Ada which I do know, how would you use the same discriminant across multiple Rust enums and guarantee that you implemented variants for each discriminant value?

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?


Replies

bombela • yesterday at 11:49 PM

  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(()),
      }
  }
➕ show 1 reply
afdbcreid • yesterday at 11:10 PM

Why do you need to do that? You can't be generic over "any enum using this tag" anyway (in Rust, at least). If you just want to make sure you make no mistake, you can use a dead match from the tag to the enum, or automate it with a macro, and the compiler will enforce exhaustiveness (though not on both sides, unless you use a macro).

➕ show 1 reply