Empty non-null Associative Arrays should be trivial or even the default.

Mike Parker aldacron at gmail.com
Tue Aug 3 16:20:50 UTC 2021


On Tuesday, 3 August 2021 at 15:51:43 UTC, Rekel wrote:
> Having to insert dummy variables into an associative array in 
> order to initialize it (and prevent foreach loops from throwing 
> a range violation error) seems very dirty to me. Why is there 
> no syntax for empty initialization?


Associative arrays are initialized as empty by default. The 
following compiles and prints nothing, as expected:

```d
int[string] aa;
foreach(k, v; aa) writeln(v);
```

What are you doing that causes the range violation?


> Suddenly getting a nullpointer after removing a ~= in an 
> entirely different part of my code is 1 (VERY problematic) 
> thing, but I'm even more surprised by the possible 'fixes'. . . 
> (which would be either a useless insertion & removal procedure 
> or a nullpointer check I will never again need after initial 
> steps.)
>

You mean, doing something like `aa["foo"]` gives you the range 
violation? That's intended. If the key was never assigned, it's 
just like trying to index a normal array with a value that's out 
of bounds. The proper way to check for an element in an AA is via 
`in`, which returns a pointer to the element if it exists and 
null if it doesn't:

```d
int[string] aa;
if(auto v = "foo" in aa) writeln(*v);
else writeln("No foo.");
```

See:
https://dlang.org/spec/hash-map.html#testing_membership



More information about the Digitalmars-d mailing list