On Tuesday, 4 September 2018 at 11:25:15 UTC, Alex wrote:
On Tuesday, 4 September 2018 at 10:30:24 UTC, Timoses wrote:
However, of course this also fails because randomly assigning
the array elements will overwrite it. So the associative array
seems like the better idea. However, not being able to
INITIALIZE an assoc array element disallows its usage.
Is there any solution, trick or workaround??
I tried two workarounds:
1) let the immutable away.
2) preallocate a full array of immutables. Then, misuse the
assoc array by using the keys only. If the key is there, then,
yield the appropriate element from the preallocated array. If
not, yield the "elephant in Cairo".
I also had this problem recently. I think aa.require() should
allow to add immutables (feature request). Anyway, my workaround
was along the lines of:
final class AA(Key, Value)
{
Value[] _storage;
size_t[Key] _aa;
void opIndexAssign(Value value, Key key)
{
if (key !in _aa)
{
_storage ~= value;
_aa[key] = _storage.length - 1;
}
}
Value opIndex(Key key)
{
if (auto index = key in _aa)
return _storage[*index];
throw new Exception("no key");
}
}
immutable struct S
{
int num;
}
void main()
{
import std.stdio : writeln;
auto aa = new AA!(string, S);
aa["one"] = S(1);
aa["two"] = S(2);
writeln(aa["one"]);
writeln(aa["two"]);
}