Thread overview
how to initialize nested struct elegantly?
Dec 12, 2018
elvisxzhou
Dec 12, 2018
elvisxzhou
December 12, 2018
import std.stdio;

struct AA
{
    int i;
    char c;
    double d;
    string s;
    float f;
}

struct BB
{
    float f;
    AA[2] a;
}

void print(BB* bb)
{
    writefln("bb.a[0].i=%d bb.f=%f", bb.a[0].i, bb.f);
}

void main()
{
    //dlang
    AA aa = {
        i:1010,
        f:0.1f
    };

    BB bb = {
        f : 0.2f,
        a : [
                AA(1010, 0,0,null,0.1f),
                AA(1020,0,0,null,0.2f)
            ]
    };

    print(&bb);

    /************************************************/
    /*

    //C99
    print( &(BB){
        .f = 0.2f,
        .a = {
            [0] = { .i = 1010, .f = 0.1f }
            [1] = { .i = 1020, .f = 0.2f }
        }
    });

    */
}


dlang version has two unnecessary symbols aa and bb, which is ugly compare to c99 one.

December 12, 2018
On Wednesday, 12 December 2018 at 09:49:58 UTC, elvisxzhou wrote:
> import std.stdio;
>
> struct AA
> {
>     int i;
>     char c;
>     double d;
>     string s;
>     float f;
> }
>
> struct BB
> {
>     float f;
>     AA[2] a;
> }
>
> void print(BB* bb)
> {
>     writefln("bb.a[0].i=%d bb.f=%f", bb.a[0].i, bb.f);
> }
>
> void main()
> {
>     //dlang
>     AA aa = {
>         i:1010,
>         f:0.1f
>     };
>
>     BB bb = {
>         f : 0.2f,
>         a : [
>                 AA(1010, 0,0,null,0.1f),
>                 AA(1020,0,0,null,0.2f)
>             ]
>     };
>
>     print(&bb);
>
>     /************************************************/
>     /*
>
>     //C99
>     print( &(BB){
>         .f = 0.2f,
>         .a = {
>             [0] = { .i = 1010, .f = 0.1f }
>             [1] = { .i = 1020, .f = 0.2f }
>         }
>     });
>
>     */
> }
>
>
> dlang version has two unnecessary symbols aa and bb, which is ugly compare to c99 one.

aa is already eliminated in the example, but you know where the ugly is.
December 12, 2018
On 12/12/18 4:49 AM, elvisxzhou wrote:
> dlang version has two unnecessary symbols aa and bb, which is ugly compare to c99 one.
> 

Well, this works:

    BB bb = {
        f : 0.2f,
        a : [
            {i:1010, f:0.1f}, // note the nested field name syntax
            {i:1020, f:0.2f}
            ]
    };

    writeln(bb);

But you can't use that syntax for expressions, only for initialization.

So, no you can't get rid of the bb if you want to use that syntax.

Or you can just create a factory function to do what you want.

-Steve