Generating custom toString for structs

Renato renato at athaydes.com
Sun Jan 7 09:49:36 UTC 2024


Hi, I wanted to customize the toString implementation for my 
structs.

So I wrote a mixin for doing that:

```
import std.traits : FieldNameTuple;
import std.format : FormatSpec;
import std.conv : to;
import std.range : put;

private mixin template StructToString(S)
{
     void toString(scope void delegate(const(char)[]) sink,
         FormatSpec!char fmt)
     {
         put(sink, typeid(S).toString);
         put(sink, "(\n");
         foreach (index, name; FieldNameTuple!S)
         {
             put(sink, "  ");
             put(sink, name);
             put(sink, ": ");
             put(sink, this.tupleof[index].to!string);
             put(sink, ",\n");
         }
         put(sink, ")");
     }
}
```

I would've expected this sort of thing (various ways of 
implementing toString for structs and classes) to be already 
provided by some library but I couldn't find any.

Anyway, my questions are:

Is the above a "good" way to do this?

Are there libraries (or even something in Phobos?) that already 
provide some mixins or equivalent functionality?

For reference, I wanted something like Java [Lombok's ToString 
annotation](https://projectlombok.org/features/ToString), also 
present in 
[Groovy](https://docs.groovy-lang.org/latest/html/gapi/groovy/transform/ToString.html).


More information about the Digitalmars-d-learn mailing list