associative arrays with arrays as value

bearophile bearophileHUGS at lycos.com
Sun Apr 19 01:16:44 PDT 2009


MLT:
> Why is that?

I think this is the right syntax (I am using Phobos on D1):

import std.stdio: writefln;
void main() {
    int[5][string] aa = ["a": [1, 2, 3, 4, 5]];
    aa["b"][] = aa["a"]; # line 5
    writefln(aa);
}

But it gives an:
Error: ArrayBoundsError temp(5)
It looks like a bug. Static arrays will need to be improved in D, they have lot of bugs/limits.

Note that in the current D there's a way to walk around that problem, you can wrap your static array into a struct. Here I use my Record (from my dlibs) that defines on the fly a struct that has several smart methods, among them there are opEquals, onHash, opCmp, toString, etc:
http://www.fantascienza.net/leonardo/so/libs_d.zip

import std.stdio: writefln;
import d.templates: Record;
import d.string: putr;

alias Record!(int[5]) R;

void main() {
    R[string] aa = ["a": R([1, 2, 3, 4, 5])];
    aa["b"] = aa["a"];
    writefln(aa);
    putr(aa);
}

This works, and prints:
[a:record([1, 2, 3, 4, 5]),b:record([1, 2, 3, 4, 5])]
["a": record([1, 2, 3, 4, 5]), "b": record([1, 2, 3, 4, 5])]

Bye,
bearophile


More information about the Digitalmars-d-learn mailing list