Newbie style question about string constants

Ian ian at iangarcia.net
Sun Mar 16 15:22:04 UTC 2025


On Tuesday, 25 February 2025 at 00:34:45 UTC, Jonathan M Davis 
wrote:
> For strings, the way that you normally do constants is with 
> enum, e.g
>
>     enum foo = "dlang";
>
> An enum like this is called a manifest constant. And you use 
> manifest constants for most constants in D, with the caveat 
> that for anything other than a string which involves an 
> allocation, you probably don't want to use an enum. That's 
> because enums are not variables, and their values are 
> essentially copy-pasted wherever they're used. So, if you do 
> something like
>
>      enum foo = [1, 2, 3];
>
> everywhere that you use foo, it'll be the same as if you used 
> [1, 2, 3] directly. And because [1, 2, 3] allocates a new 
> array, that means that each use of the enum allocates a new 
> array. In such a situation, using a static variable would be 
> better, e.g.
>
>     static immutable foo = [1, 2, 3];
>
> That does create a variable, so wherever you use foo, the array 
> is sliced (so you get two arrays referring to the same piece of 
> memory) rather than resulting in a new allocation.
>
> [. . .]
>

Somehow I missed all of these responses. Thank you.

It seems that in some cases static immutable is preferred, so why 
not use that always then, rather than having to keep two cases in 
my head?

  Ian


More information about the Digitalmars-d-learn mailing list