digitalmars.D.learn - Printing struct fields and values
- z (29/29) Jan 22 A simple function to dump a struct's fields:
- Richard (Rikki) Andrew Cattermole (22/22) Jan 22 ```d
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
```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








"Richard (Rikki) Andrew Cattermole" <richard cattermole.co.nz>