Can structs be used with associative arrays?

Chris Nicholson-Sauls ibisbasenji at gmail.com
Sun Apr 30 00:41:43 PDT 2006


Tim Locke wrote:
> On Wed, 20 Jul 2005 20:46:26 -0400, "Ben Hinkle"
> <ben.hinkle at gmail.com> wrote:
> 
> 
>>>int main()
>>>{
>>>   A[char[]] x;
>>>   x["a"] = *(new A); // Create an instance of the struct.
>>>   x["a"].a = 1;
>>>   return( 0 );
>>>}
>>
>>Note the *(new A) will allocate a new A and then copy the contents to x["a"] 
>>and then throw away the allocated memory. So a way of doing the same thing 
>>without allocating extra memory is to
>>x["a"] = A.init; 
> 
> 
> What is the concise method of initializing the members of my array of
> structs? It seems long-handed to do this:
> 
> x["a"].a = 1;
> x["a"].b = 2;
> etc.
> 
> Can this be shortened? According to spec_DMD_0.109.pdf, pages 100-101,
> I *think* I should be able to do something like this:
> 
> x["a"] = {a:1, b:2};
> 
> But the compiler gives me the following error: "expression expected,
> not '{'". I also tried replacing {} with () and got "found ':' when
> expecting ')'".
> 
> Thank you.
> --
> On the Internet, no one knows you're [using] a VIC-20.

The {a:1, b:2} format is the struct static initializer syntax, used with static and const 
declerations only, sadly.  Hopefully in the future it becomes more general purpose 
(related issues to array literals).  While it isn't perfect, you can do this, which at 
least reduces the number of array lookups to one:

# with (x["a"]) { a = 1; b= 2; }

In fact, I guess you could technically even do:

# with (x["a"]) a = 1, b = 2;
# with (x["b"] = A.init) a = 1, b = 2;

So long as with() doesn't require braces after it.  (I think it does, mostly because 
nobody ever thought of a case where you wouldn't need them... suppose I just did.)

-- Chris Nicholson-Sauls



More information about the Digitalmars-d-learn mailing list