Enum literals, good? bad? what do you think?

Steven Schveighoffer schveiguy at gmail.com
Wed Jul 21 13:36:37 UTC 2021


On 7/20/21 11:50 AM, russhy wrote:
> Hello
> 
> I all the time wondered why we always have to be so much verbose with 
> enum, when it's not casting to primitives, it is about repeating their 
> long type name, constantly, all the time
> 
> After trying some other languages over the past few years, i discovered 
> in zig you can just ommit the enum type name and just use enums this 
> way: .MY_VALUE
> 
> I don't know if that's something that could be supported with D, i am 
> not a compiler dude, so i don't have the answer
> 
> Adam on discord mentioned using with(ENUM_TYPE) or just an alias, but i 
> think we go ahead and make it simple
> 
> I had prepared a DIP [1], not ready at all, but i wanted to initiate 
> some discussion about that feature
> 
> So what do you think? yay? nay? why not?
> 
> 
> [1] https://github.com/RUSshy/DIPs/blob/patch-2/DIPs/DIP1xxx.md

I enjoy having this type of shortcut in Swift, and wish D had something 
similar.

To give some perspective, look no further than configuration options of 
std.algorithm:

```d
arr.sort!("a < b", .unstable); // instead of SwapStrategy.unstable
```

Clear as the original, and less verbose. In Swift, enums are used 
extensively, and I don't think they would be if the shortcut syntax 
wasn't available.

And in general, any function parameter enums are cumbersome to write in D.

However, using `.enumMember` isn't viable as noted by several people.

If I were to propose something, it would be to have a short substitute 
for the type. Something like `#.typeMember` which then uses the 
expression type to lookup the member. Then you can do things like 
`#.init` or any other type properties that return an instance of the 
type. It wouldn't be a panacea though, since overloading would make this 
ambiguous. But assignment/initialization would be unambiguous.

Probably not going to fly in D.

-Steve


More information about the Digitalmars-d mailing list