Getting nice print of struct for debugging

Martin Tschierschke via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Feb 27 02:55:42 PST 2017


On Saturday, 25 February 2017 at 01:30:09 UTC, Minty Fresh wrote:
> On Saturday, 25 February 2017 at 01:27:09 UTC, Minty Fresh 
> wrote:
>> On Wednesday, 22 February 2017 at 11:18:15 UTC, Martin 
>> Tschierschke wrote:
>>> [...]
>>
>> Since structs are Plain-old Data and don't do inheritance, the 
>> best option is a template mixin.
>>
>> ie.
>>
>>   template mixin PrettyPrint
>>   {
>>       string toString()
>>       {
>>           // . . .
>>       }
>>   }
>>
>> From there, you can mix it into any struct you want.
>>
>>   struct MyStruct
>>   {
>>       mixin PrettyPrint;
>>   }
>>
>> If you're familiar with Rails, this is similar to a Concern.
>
> Errata on that. Should actually be declared as:
>
>   mixin template PrettyPrint()
>
> This is why I shouldn't make posts from my phone.

Thank you, but this solution from Kevin Brogan, is an good 
alternative,
to add a special dump function globally, so no need to modify the 
struct definitions.

https://forum.dlang.org/post/yewavntuyutdvejwjamp@forum.dlang.org

His solution:

import std.traits;

void main()
{
	WSADATA wsa;
	dump!wsa;
}

void dump(alias variable)()
{
	writeln("\nDumping ",typeid(typeof(variable)),":\n");
	writeln(variable.stringof, " = \n{");
	foreach(member; FieldNameTuple!(typeof(variable)))
	{
		writeln("\t", member, ": ", mixin("variable."~member) );
	}
	writeln("}\n");
}





More information about the Digitalmars-d-learn mailing list