use variant as associative array
Daniel Keep
daniel.keep.lists at gmail.com
Thu Feb 11 22:50:19 PST 2010
GG wrote:
> Yes I can't use struct and/or enum because I can't know type and number of data that user could pass.
> In this example, we talk about Month, but it could be Minutes, week... So I try to program dynamic not static.
If you're trying to program dynamically, then you're using the wrong
language. Writing dynamically-typed code in D is like trying to write C
in Python; it's missing the language's strengths.
> In fact I'm learning D thought a little project of graphic chart. I would like to keep a notion that I have found very usefull in AS3 : ArrayCollection.
AS3 is dynamically typed; D is not. Variant can be used to 'fake'
dynamic typing, but only to a certain degree. You can't call methods on
Variants, operations on them are kinda flaky, etc.
> I just want to know if it possible in D to have only one BIG collection of any type of data (int,string,bool,double...) ?
Arrays of Variant.
> We talk about Variant but it could be other ? Maybe not...
>
> So I tried this :
> Variant[char[]][int] aa;
>
> aa[0]["Month"] = Variant("Jan"); // compile
> aa[0]["Profit"] = Variant(500); // compile
>
> aa[1]["Month"] = Variant("Feb"); // compile
> aa[1]["Profit"] = Variant(800); // compile
>
> for(int i=0;i<aa.length;i++) // compile failed on aa.length and get dmd: mtype.c:3426: StructDeclaration* TypeAArray::getImpl(): Assertion `impl' failed.
AAs don't have a length (as far as I remember). Besides which, there's
NOTHING that says the keys for aa are sequential. If you want a
sequence, use an array.
You should probably read the documentation on how to use AAs.
> {
> writefln("%s",aa[i]["Month"]); // compile but get at runtime : core.exception.RangeError at test(25): Range violation
> }
What you want is probably more along these lines:
foreach( k,v ; aa )
{
writefln("%s", v);
}
> It seems to be a bug...
>
> Thanks !
More information about the Digitalmars-d-learn
mailing list