Getting nice print of struct for debugging

Paul Backus via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Feb 20 08:18:58 PST 2017


On Monday, 20 February 2017 at 16:04:17 UTC, 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.

I believe the easiest way to do this is to define a custom 
toString member function for your struct. For example:

struct MyStruct {
     int x;
     double y;
     string s;

     string toString() {
         import std.format: format;

         return "MyStruct(x: %d, y: %f, s: \"%s\")".format(x, y, 
s);
     }
}

void main() {
     import std.stdio: writeln;

     MyStruct foo;
     foo.x =2; foo.y = 3.14; foo.s = "the quick brown fox";

     writeln(foo); // Prints MyStruct(x: 2, y: 3.140000, s: "the 
quick brown fox")
}



More information about the Digitalmars-d-learn mailing list