What is the shortest way to define an immutable token of unique type?

Petar Petar
Sun Mar 14 19:10:19 UTC 2021


On Sunday, 14 March 2021 at 16:37:58 UTC, Andrei Alexandrescu 
wrote:
> Is there a simpler way that this?
>
> struct Hex {}
> immutable Hex hex;
>
> I don't want to introduce two names in the scope, just `hex`. 
> Another attempt:
>
> immutable hex = function {};

Could be slightly shorter:

const u = (){};

> That's a bit... arcane. Is there another simple way? Thanks!

Indeed, though what is your use case? Usually the use case 
determines whether a solution is good or not.

Is JavaScript's Symbol [1] primitive data type something like 
what you're after?

Perhaps anonymous classes would be closest D can offer - `auto a 
= new class {};`. Unfortunately, unlike struct values, classes 
objects can't pass through from CTFE to RT, which makes them 
limited for certain use cases (e.g. you can't put the statement 
above at the module scope).

[1]: https://developer.mozilla.org/en-US/docs/Glossary/Symbol


More information about the Digitalmars-d mailing list