www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - associative arrays with arrays as value

reply MLT <none anon.com> writes:
I am just learning D, and playing around. So I have no good reason why one
would do the following, but I also don't understand why it doesn't work...

I was trying to make an associative array with int[5] as the value type. That
didn't work properly. int[] did, and I don't understand why.
Here is what worked:

module main ;
import tango.io.Stdout ;

void main()
{
  int[] [char[] ] x = [ "a":[1,2,3,4,5] ] ;
  x["b"] = x["a"] ;
  Stdout(x).newline ; 
}

and here is what didn't:

void main()
{
  int[5] [char[] ] x = [ "a":[1,2,3,4,5] ] ;
  x["b"] = x["a"] ;
  Stdout(x).newline ; 
}

(Only diffence is the 5 in the int[5][ char[] ]x)
The error I get (with gdc) is: Error: cannot assign to static array x["b"]
I tried many other versions of the assignment x["b"][] =, x["b"]=[1,2,3,4,5],
etc. But nothing work.

Why is that?
Apr 18 2009
parent bearophile <bearophileHUGS lycos.com> writes:
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]]; 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
Apr 19 2009