Hacker News new | ask | show | jobs
by tomjakubowski 3831 days ago
Can you name the variants to distinguish two variants which "carry" the same types? It wouldn't be as useful if you can't express something like:

    enum ConnState {
        Disconnected,
        Connecting,
        Connected(net::TcpSocket),
        Transferring(net::TcpSocket),
     }
2 comments

I would probably do it like this in D (disclaimer: I haven't tested this code!)

  import std.typecons;
  import std.socket;
  import std.variant;

  struct Disconnected {}
  struct Connecting {}

  alias Connected = Typedef!(TcpSocket, null, "connected");
  alias Transferring = Typedef!(TcpSocket, null, "transferring");

  alias ConnState = Algebraic!(Disconnected, Connecting, Connected, Transferring);
You could use plain structs instead of the typedef template for the same result.
I see what you mean.

You can create such new types with std.typecons.Typedef https://dlang.org/phobos/std_typecons.html#.Typedef

Though it's less pretty.