Semantics of toString

Bill Baxter wbaxter at gmail.com
Tue Nov 10 08:56:25 PST 2009


On Tue, Nov 10, 2009 at 7:29 AM, Don <nospam at nospam.com> wrote:
> Bill Baxter wrote:
>>
>> On Tue, Nov 10, 2009 at 4:40 AM, Don <nospam at nospam.com> wrote:
>>>
>>> Lutger wrote:
>>>>
>>>> Don wrote:
>>>> ...
>>>>>
>>>>> There is a definite use for such as thing. But the existing toString()
>>>>> is much, much worse than useless. People think you can do something
>>>>> with
>>>>> it, but you can't.
>>>>> eg, people have asked for BigInt to support toString(). That is an
>>>>> over-my-dead-body.
>>>>
>>>> Since you are in the know and probably the biggest toString() hater
>>>> around: are there plans (or rejections thereof) to change toString()
>>>> before
>>>> D2 turns gold? Seems to me it could break quite some code.
>>>
>>> I'm hoping someone will come up with a design.
>>>
>>> Straw man:
>>>
>>> void toString(void delegate(const(char)[]) sink, string fmt) {
>>>
>>> // fmt holds the format string from writefln/formatln.
>>> // call sink() to print partial results.
>>>
>>> }
>>
>> That looks pretty good, actually.
>> I guess I would like to see plain no-arg toString() still supported.
>
> The thing is, the toString() function is essentially a virtual function
> present in every struct. Each one of those functions needs a very strong
> justification to exist.

Structs can't have virtual functions... so what do you mean?

>> A default toString() could be implemented in terms of the fancy one as:
>>
>> string toString() {
>>     char buf[];
>>     toString( (string s) { buf ~= s; }, "" );
>>     return assumeUnique!(buf);
>> }
>>
>> could be a mixin in a library I suppose.
>
> More for the benefit of consumers, or producers?

Consumers.  I was just thinking it would be a little annoying to have
to reproduce the above 3-line snippet of code every time I want to get
the string version of an object.

But I guess such needs can be adequately served by std.string.format
or sformat.  So scratch that, no old-style toString() needed.

> Because
> void toString(void delegate(const(char)[]) sink, string fmt) {
>   sink("xxx");
> }
> isn't much more complex than:
> string toString()
> {
>  return "xxx";
> }
> other than the signature.

Yeh, for authors of toString methods it's fine.

Well, a different way to write delegates would be nice, but that's a
different discussion.

>> I think I would like to see the format strings not necessarily tied to
>> writefln's particular format.
>
> I think the format strings are actually pretty similar, Tango vs writefln?
> There might be enough common ground. I think the Tango format is a slight
> superset of the writefln one.

Pretty similar, maybe, but I'd be surprised if they just happened to
be identical without any attempt at compatibility having been made.

--bb



More information about the Digitalmars-d mailing list