[Dlang-internal] Const or invariant key in dynamic array

Richard Andrew Cattermole (Rikki) richard at cattermole.co.nz
Mon Aug 24 02:11:24 UTC 2026


On Monday, 24 August 2026 at 02:04:10 UTC, Valentino Giudice 
wrote:
> Hi.
>
> Consider the following snippet:
>
> ```D
> int[int] darr;
> darr[0] = 0;
> int k1 = 1;
> darr[k1] = 1;
> immutable k2 = 2;
> darr[k2] = 2;
> ```
>
> The code declares a sparse array as a dynamic array with int as 
> a type for both keys and values.

Associative array, not a dynamic array.

> If I place the code in a `@safe` context, the compiler warns me:
>
>> Deprecation: using the result of a cast from `immutable(int)` 
>> to `int` as an lvalue will become `@system` in a future release
>
> Because key values only need to be read, not written to, I'd 
> argue that this code should be fine in a safe context.
>
> If the type of key is a composite one and it happens to contain 
> pointers, references or dynamic arrays, then this prohibition 
> actually makes sense.
>
> A user could iterate over keys, which would be returned as 
> modifiable objects, then modify the referenced objects from 
> there even if the key was originally created from a constant 
> object.
>
> However, when the key type is a simple type or a struct type 
> which contains no references, pointers or dynamic arrays, I'd 
> argue this code should be allowed in a safe context.
>
> In fact, `T1[T2]`, `T1[const T2]` and `T1[immutable T2]` should 
> be regarded as the same type.
>
> Granted, what I referenced is only a warning for now, but I 
> hope it will be possible to use key values this way.

So basically to clarify:

As long as a struct is by-value, is POD, allow mutable, otherwise 
require immutable.

Note that const isn't suitable for keys of a map.


More information about the Dlang-internal mailing list