What is the difference between enum and shared immutable?

H. S. Teoh hsteoh at quickfur.ath.cx
Wed Oct 28 22:07:06 UTC 2020

On Wed, Oct 28, 2020 at 09:54:19PM +0000, Jan Hönig via Digitalmars-d-learn wrote:
> Maybe this is a silly question, but I don't understand completely the
> difference between an `enum` and a `shared immutable`.
> I could have:
> enum x = 1;
> or
> shared immutable x = 1;
> What is the exact difference between those too?

An enum only exists at compile-time, and does not occupy any space. Each
time it's referenced, a new instance of the value is created.  (This is
why it's a bad idea to use enum with an array literal, because every
time it's referenced you get a new copy of the array.)

A shared immutable is initialized at compile-time, and occupies space in
the object file / runtime memory. It's also a single instance, and
referencing it causes a load of this instance at runtime.  It's not
copied unless it's a by-value type, so an array literal will get stored
as an array in the executable, and every time you reference it you get a
slice of it instead of a copy.


In order to understand recursion you must first understand recursion.

More information about the Digitalmars-d-learn mailing list