Getting nice print of struct for debugging
Jacob Carlborg via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Tue Feb 21 06:02:54 PST 2017
On 2017-02-20 17:04, Martin Tschierschke wrote:
> Hello,
> I have a little program where I am filling a struct with values from an
> regex match.
> Now I want to display the content of the struct for debugging purpose.
>
> If struct is named MyStruct
>
> I can print a list of the field names with:
>
> foreach(fieldname;FieldNameTuple!MyStruct){writef("%s ",fieldname);}
>
> If myvar is of type MyStruct how can I make a table like:
>
> fieldname_1: value_1
> fieldname_2: value_2
> .
> .
> fieldname_n: value_n
>
> Is there a way to do this with a single expression in D.
>
> Similar to a ruby call myvar.send(fieldname) to get the value from
> fieldname inside a loop?
> write(myvar); sure is working directly but I want to get the field names
> displayed, too.
>
> (A work around might be work with the format("%s",myvar) string and
> extract the values with an index?)
Yes, this works, I would say this is the simplest:
MyStruct s;
foreach (index, name ; FieldNameTuple!MyStruct)
writefln("%s: %s", name, s.tupleof[index]);
If you want something more close to "send" in Ruby, you need to use a
string mixin, like this:
foreach (name ; FieldNameTuple!MyStruct)
writefln("%s: %s", name, mixin("s." ~ name));
The string mixin example works for methods, opDispatch and similar as
well. The tupleof example, the first one, works only for fields.
--
/Jacob Carlborg
More information about the Digitalmars-d-learn
mailing list