Newbie style question about string constants
Jonathan M Davis
newsgroup.d at jmdavisprog.com
Mon Mar 17 08:27:17 UTC 2025
On Sunday, March 16, 2025 9:22:04 AM MDT Ian via Digitalmars-d-learn wrote:
> 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?
You can do whatever you want, but static immutable variables are variables,
and enums are not, so they behave differently. And if you don't understand
the differences, you could have problems understanding code that other
people write or understanding why the compiler lets you do something in one
case but not another.
In any case, the normal way in D to declare a string constant is to use
enum. So, that's primarily what you're going to see in most code. Whether
you choose to do that in your own code is up to you.
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list