Initialization of struct containing anonymous union

Steven Schveighoffer via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Aug 14 07:24:40 PDT 2017


On 8/14/17 9:49 AM, Carl Sturtivant wrote:
>    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

I think what the docs mean is that as soon as an anonymous union is 
present, you can't initialize anything further than the first union field.

> 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?

I think the only way to solve it is with a constructor:

this(int ival, double xval) { i = ival; x = xval; }

-Steve


More information about the Digitalmars-d-learn mailing list