DIP9 -- Redo toString API

spir denis.spir at gmail.com
Mon Nov 22 02:04:54 PST 2010


On Mon, 22 Nov 2010 10:14:03 +0100
Don <nospam at nospam.com> wrote:

> Tomek Sowiński wrote:
> > Don <nospam at nospam.com> napisał(a):
> > 
> >> The efficiency issues are important, but are not the primary motivation.
> >> toString() is just wrong. The idea that there is ONE AND ONLY ONE 
> >> textual representation of an object, is, frankly, idiotic.
> > 
> > I always thought of toString() as an aid in debugging, where having one 
> > and only way to print out an object makes sense. 
> 
> It isn't just used in debugging. It's used for writefln.
> But even for debugging, it doesn't work.
> 
> If I have a struct:
> 
> struct Foo
> {
>     Complex!(double) val;
> }
> 
> and, for debugging purposes, I want to write 'val' to 10 decimal places.
> How do I do that?

I agree with you. toString lacks flexibility in some (not very common but relevant) cases, that would be brought by an optional format specifier. I would enjoy beeing able to write this with toString, instead of a custom text() method:

struct Complex {
    float r,i;
    string text(string numberFormat="%.3f") {
        string outFormat = format("%s+%sj", numberFormat,numberFormat);
        return format(outFormat, this.r,this.i);
    }
}
void main () {
    auto c = Complex(1.11111,3.333333333);
    writeln(c.text());
    writeln(c.text("%.7f"));
}
==>
1.111+3.333j
1.1111100+3.3333333j


But, to be fair, does this have anything to do with the current <writeTo vs toString> debate?
The only actual point of said debate is efficiency.


Denis
-- -- -- -- -- -- --
vit esse estrany ☣

spir.wikidot.com



More information about the Digitalmars-d mailing list