Nothing type/value aka Unit

Meta jared771 at gmail.com
Fri Feb 8 14:28:23 UTC 2019


On Friday, 8 February 2019 at 13:32:22 UTC, Jonathan Levi wrote:
> In D what would be the most appropriate type for a value that 
> specifically does not carry a value?
>
> I am working on porting Sodium, a simple FRP library, to D (or 
> making one like it).  In FRP, events (aka event occurrences) 
> must contain 1 and only 1 value.  So when there is no 
> appropriate value, they make its value what they call a Unit.
>
> For the java version of Sodium they define the unit like `enum 
> Unit { UNIT }`.  In Haskell when this thing is needed `()` is 
> used (an empty tuple).
>
> Is there a more appropriate way to do this in D?  Perhaps in 
> Phobos?
>
> What makes more sense then `enum Unit { unit }` to me is 
> `struct Unit {}; enum Unit unit;`.

There's no canonical unit type in D, so I'd recommend going with 
whichever fits best for your use case. A couple built-in ones 
would be an enum with a single value or a struct with no fields 
(as you already mentioned), as well as the `void` type (but D 
doesn't let you construct a value of type void), as well as 
`typeof(null)`, which has `null` as its only value.


More information about the Digitalmars-d mailing list