Static array as immutable

Jonathan M Davis newsgroup.d at jmdavisprog.com
Tue Dec 12 09:48:09 UTC 2017


On Tuesday, December 12, 2017 07:33:47 Ivan Trombley via Digitalmars-d-learn 
wrote:
> Is there some way that I can make this array immutable?
>
>    static float[256] ga = void;
>    static foreach (i; 0 .. 256)
>        ga[i] = (i / 255.0f) ^^ (1 / 2.2f);

If you want anything to be immutable, you either have to initialize it
directly or give it a value in a static constructor (and the static
constructor solution won't work for local variables). So, you'd need to do
something like

static immutable float[256] ga = someFuncThatGeneratesGA();

If the function is pure, and there's no way that the return value was passed
to the function, then its return value can be assigned to something of any
mutability, since the compiler knows that there are no other references to
it, and it can implicitly cast it, or if the type is a value type (as in
this case), then you just get a copy, and mutability isn't an issue.
Alternatively to using a pure function, you can use
std.exception.assumeUnique to cast to immutable, but that relies on you
being sure that there are no other references to the data, and it may not
work at compile-time, since casting is a lot more restrictive during CTFE.
So, in general, using a pure function is preferable to assumeUnique.

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list