anonymous structs within structs

Mike Shah mshah.475 at gmail.com
Mon Dec 4 21:55:29 UTC 2023


On Monday, 4 December 2023 at 18:26:07 UTC, DLearner wrote:
> Suppose we need a construct like:
> ```
> void main() {
>
>    struct A {
>       int I1;
>       int I2;
>       char X;
>    }
>
>    struct B {
>       A Dummy;
>       int Var1;
>       int Var2;
>    }
> }
> ```
> But do not want to give an explicit name (like 'Dummy' above) 
> to the A struct held within the B struct.
>
> Just removing 'Dummy' does not work (Error: no identifier for 
> declarator `A`).
> Nor does replacing 'Dummy' with {}
>
> Suggestions?

One possible solution is to use a 'mixin template' where you 
effectively 'copy and paste' in the 'struct' and access the 
symbols.

Is something like this what you had in mind?

```
void main() {
    import std.stdio;

    mixin template A() {
       int I1;
       int I2;
       char X;
    }

    struct B {
       mixin A;
       int Var1;
       int Var2;
    }

         B someObject;
         writeln(someObject.I1);
         writeln(someObject.I2);
}
```


More information about the Digitalmars-d-learn mailing list