Customizing printing of structs (writeln / to!sth behavior).

cym13 via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Feb 15 04:10:59 PST 2016


On Monday, 15 February 2016 at 12:03:44 UTC, ciechowoj wrote:
> It there a way to change how writeln converts structs to 
> strings? I read in the documentation it uses to!string to 
> convert the struct. Is there a way to overload to!string for my 
> own type?
>
> Let say I have:
>
> struct Point {
>     int x, y;
> }
>
> and I want writeln(Point(3, 4)); to print "[3, 4]" instead of 
> "Point(3, 4)".

Just define a toString method, it will be used by .to!string

     struct Point {
         int x;
         int y;

         string toString() {
             import std.format: format;
             return format("[%d, %d]", x, y);
         }
     }

     void main(string[] args) {
         import std.stdio: writeln;

         auto p = Point(3, 4);
         p.writeln; // [3, 4]
     }



More information about the Digitalmars-d-learn mailing list