Pretty print struct field values

Andrej Mitrovic none at none.none
Sun Apr 24 14:11:09 PDT 2011


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?


More information about the Digitalmars-d-learn mailing list