Yes, thanks, that syntax does work for the initialization.

The C syntax that failed for me was using the curly brace form shown in the following link.

http://www.c4learn.com/c-programming/c-initializing-array-of-structure/

Also, I think I was trying forms of defining the struct and initializing the array in the same line... something like this C: static struct Suit{ int i; long lv;} suits[3] = {{1, 2L},{2, 4L},{3,9L}};

It looks to me like D requires a named struct definition in a separate line from the array definition. If that is so, then the C initialization of an array with an unnamed struct type, like this, would require a struct type name.

static struct { int i; long lv;} suits[3] = {{1, 2L},{2, 4L},{3,9L}};

So, from your static intialization example, this works.

Also, the conversion of struct to tuple makes the writefln tupleof conversion on the struct a little cleaner, since you only have to specify the single tuple parameter.


module main;

import std.stdio;

void main()
{
        struct Suit {string nm; int val; int val2; string shortNm;};

        static Suit[5] suits =  [
                {"spades",1,6,"spd"},
                {"hearts",4,10,"hrt"},
                {"hearts2",4,10,"hrt2"},
                {"diamonds",10,16,"dmd"},
                {"clubs",11,17,"clb"}
                ];
        
    foreach (member;  suits)
    {
        auto tup = member.tupleof;
        writefln("%s %d %d %s", tup);
    }

}

prints
spades 1 6 spd
hearts 4 10 hrt
hearts2 4 10 hrt2
diamonds 10 16 dmd
clubs 11 17 clb

I also tried using writefln(tup) and writeln(tup) in the example above. The output from writeln(tup) looks like it is headed in the right direction. Maybe a writecsv(tup) would be useful.

spades16spd
hearts410hrt
hearts2410hrt2
diamonds1016dmd
clubs1117clb

Reply via email to