Avoiding GC in D and code consistancy

Steven Schveighoffer schveiguy at yahoo.com
Sun Dec 31 12:50:34 UTC 2017


On 12/31/17 6:16 AM, Tim Hsu wrote:
> On Sunday, 31 December 2017 at 07:32:50 UTC, Ali Çehreli wrote:
>> On 12/30/2017 11:16 PM, Tim Hsu wrote:
>>
>> > Struct version of Vector3f can't derive toString
>> > method. writeln() prints unformated struct members. I know I
>> can use
>> > helper function here. But is there any other way?
>>
>> The normal way that I know is to insert a function like the following 
>> into Vector3f:
>>
>>     string toString() {
>>         import std.string : format;
>>         return format("%s,%s,%s", x, y, z);
>>     }
>>
>> > class version of Vector3f. Require new operator in
>> opBinary(). scoped!
>> > won't work here.
>> >
>> > Is there a better to write vector3f class while avoiding GC?
>>
>> Yeah, it doesn't make sense that a type of x, y, z should be a class. 
>> I would stay with a struct here.
>>
> 
> Sorry I am a bit disappointed. It seems writeln itself will check if the 
> struct to be printed has toString. If not, it use default struct printer.

Note, you can use a "sink" version of toString as well, and avoid the gc:

void toString(void delegate(const(char)[]) sink) @nogc
{
     // use formatValue to push into the sink
}

-Steve


More information about the Digitalmars-d-learn mailing list