Initialization of struct containing anonymous union

Carl Sturtivant via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Aug 14 06:49:19 PDT 2017


   struct mess
   {
     union
     {
         int i;
         string s;
     }
     double x;
   }

How do I cleanly initialize this, assuming it's i that I want to 
give an overt value to?

The docs say "If there are anonymous unions in the struct, only 
the first member of the anonymous union can be initialized with a 
struct literal, and all subsequent non-overlapping fields are 
default initialized". This is not helpful.
https://dlang.org/spec/struct.html#struct-literal

The above is a toy example distilled from a real problem. The 
struct comes from a C library and is very long and contains 
several anonymous unions. The D declaration of the struct was 
made by someone else who made the library available to D.

I printed out such a struct returned by a call to the library, 
and wanted to create my own from scratch. But it seems that I 
can't just copy what writeln printed and edit it into an 
initialization analogous to

   mess m = { 99, 3.14 };

with the above, because I just get the analog of

Error: overlapping initialization for field i and s
Error: cannot implicitly convert expression (3.14) of type double 
to string

and the alternative more like what is printed by writeln,

   auto m = mess(99, 3.14);

produces a similar error message.

So it seems I am forced to assign explicitly to each member of 
the struct, an ugly process.

What is a nice way to solve this problem?




More information about the Digitalmars-d-learn mailing list