Pretty print struct field values

Jacob Carlborg doob at me.com
Mon Apr 25 09:06:29 PDT 2011


On 2011-04-24 23:11, Andrej Mitrovic wrote:
> This keeps popping up in my posts. Here's an example of printing out fields of a struct with its names:
>
> import std.stdio;
>
> void main()
> {
>      struct ASIOChannelInfo
>      {
>          int channel;
>          int isInput;
>          int isActive;
>          int channelGroup;
>          int type;
>          string name;
>      }
>
>      auto info = ASIOChannelInfo(1, 1, 1, 16, 32, "Analog OUT");
>
>      auto fields = __traits(allMembers, typeof(info));
>      auto values = info.tupleof;
>
>      foreach (index, value; values)
>      {
>          writef("\n%-15s %s", fields[index], value);
>      }
> }
>
> Prints:
> channel           1
> isInput            1
> isActive           1
> channelGroup 16
> type             32
> name            Analog OUT
>
> I think we could a function in Phobos that does this with a single call. Maybe it could also determine the longest field name and calculate the width specifier for the formatted output so it prints out the columns nicely. It should probably also avoid printing functions. Anyone interested in this type of function? I could give it a shot and implement it.
>
> Btw, is there a lockstep implementation that works with tuples?

I think it's a good idea. If __traits(allMembers) returns both method 
and field names then you can use Type.tupleof[0].stringof.

-- 
/Jacob Carlborg


More information about the Digitalmars-d-learn mailing list