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

Valentino Giudice valentino.giudice96 at gmail.com
Mon Aug 24 02:04:10 UTC 2026


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.

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.


More information about the Dlang-internal mailing list