Empty associative array
jfondren
julian.fondren at gmail.com
Mon Aug 9 13:21:06 UTC 2021
On Monday, 9 August 2021 at 13:10:53 UTC, Dukc wrote:
> ```d
> import std;
>
> @safe:
>
> int[int] emptyAA;
>
> void setEmptyAA()
> { alias Key = int, Value = int;
>
> emptyAA = [Key.init: Value.init];
> auto remover = emptyAA;
> remover.remove(Key.init);
> }
>
> void main()
> { setEmptyAA;
> int[int] a = emptyAA;
> int[int] b = a;
>
> b[5] = 3;
>
> a.writeln; //[5:3]
> }
> ```
>
> ...however, if you initialize `a` with `emptyAA.dup` it will
> again be `null`!
You get this with dynamic arrays as well.
```d
unittest {
int[] a;
assert(a == []);
assert(a is null);
a ~= 1;
a = a[1 .. $];
assert(a == []);
assert(a !is null);
assert(a.length == 0);
a = a.dup;
assert(a is null);
}
```
> I believe we can only conclude that empty AA's are not supposed
> to rely on being non-`null`. Sorry Walter - in my eyes this is
> a design failure.
They're very convenient, scripting-language-like types, and this
comes with a few caveats that can be emphasized in tutorials and
learned. If the convenience isn't worth the caveats for you,
there's std.container.array and perhaps
https://code.dlang.org/packages/bcaa
More information about the Digitalmars-d
mailing list