www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Printing struct fields and values

reply z <z mail.com> writes:
A simple function to dump a struct's fields:
```dlang
void inspect_struct(T)(T t)
{
    (T).stringof.writeln;
    foreach(i, member; FieldNameTuple!T)
    {
      if (isPointer!(Fields!T[i]))
      {
        // error (sometimes)
        writefln("%s %s = %s", Fields!T[i].stringof, member, 
(*t.tupleof[i]));
      }

      else
      {
        writefln("%s %s = %s", Fields!T[i].stringof, member, 
(t.tupleof[i]));
      }

    }
}
```
I would also like to automatically deref any pointers for their 
values.
This works if all fields in a struct are pointers.
But for any fields that aren't, you get an error:
```
Error: can only `*` a pointer, not a `ushort`
```
What am I missing / What would be the proper way to do this?
Jan 22
parent "Richard (Rikki) Andrew Cattermole" <richard cattermole.co.nz> writes:
```d
struct S {
     int field0;
     int* field1, field2;
}

void main() {
     import std.stdio;
     S input;
     input.field1 = new int(2);

     foreach(v; input.tupleof) {
         write(__traits(identifier, v), " = ");

         static if (is(typeof(v) : T*, T)) {
             if (v is null)
                 writeln("null");
             else
                 writeln(*v);
         } else {
             writeln(v);
         }
     }
}
```
Jan 22