Hi there. I'm currently following Ali Çehreli's "Programming in
D" book and I can't seem to be able to wrap my head around the of
delegates in the toString() functions..
http://ddili.org/ders/d.en/lambda.html
(Bottom of the page)
We have defined many toString() functions up to this point in
the book to represent objects as strings. Those toString()
definitions all returned a string without taking any
parameters. As noted by the comment lines below, structs and
classes took advantage of toString() functions of their
respective members by simply passing those members to format():
... code ...
In order for polygon to be sent to the output as a string on
the last line of the program, all of the toString() functions
of Polygon, ColoredPoint, Color, and Point are called
indirectly, creating a total of 10 strings in the process. Note
that the strings that are constructed and returned by the
lower-level functions are used only once by the respective
higher-level function that called them.
Okay, I get it.
However, although a total of 10 strings get constructed, only
the very last one is printed to the output:
[{RGB:10,10,10;(1,1)}, {RGB:20,20,20;(2,2)},
{RGB:30,30,30;(3,3)}]
However practical, this method may degrade the performance of
the program because of the many string objects that are
constructed and promptly thrown away.
I can see the reasoning behind this. But ..
However practical, this method may degrade the performance of
the program because of the many string objects that are
constructed and promptly thrown away.
An overload of toString() avoids this performance issue by
taking a delegate parameter:
CODE: void toString(void delegate(const(char)[]) sink) const;
As seen in its declaration, this overload of toString() does
not return a string. Instead, the characters that are going to
be printed are passed to its delegate parameter. It is the
responsibility of the delegate to append those characters to
the single string that is going to be printed to the output.
All the programmer needs to do differently is to call
std.format.formattedWrite instead of std.string.format and pass
the delegate parameter as its first parameter:
Why? How can a delegate which returns nothing be used as an array
which is going to be printed on the screen? And just how is it
printed? The Documentation didn't make it much clearer.. the
'sink' is supposed to be the 'writer', isn't it? So what does it
do? The arguments get interpreted and formatted into the string,
but what happens after that?
P.S. I've just checked the book, it doesn't seem to be explained
anywhere properly (the way formattedRead is)
P.P.S. I'm following the PDF version of the book