When D is not nice

superdan super at dan.org
Mon Jul 7 15:21:23 PDT 2008


Koroskin Denis Wrote:

> On Mon, 07 Jul 2008 03:12:27 +0400, superdan <super at dan.org> wrote:
> 
> > downs Wrote:
> >
> >> superdan wrote:
> >> > Ary Borenszweig Wrote:
> >> >
> >> >> Frank Benoit a écrit :
> >> >>> String concatenation in Java:
> >> >>>
> >> >>> "abc " + a + " bla";
> >> >>>
> >> >>> where a is an interface ref.
> >> >>>
> >> >>> Ported to D, this look like this:
> >> >>>
> >> >>> "abc " ~ (cast(Object)a).toString ~ " bla";
> >> >>>
> >> >>> This are 3 steps more:
> >> >>> 1.) explicit cast to Object (interface/class compatibility!)
> >> >>> 2.) explicit call to toString
> >> >>> 3.) put additional parentheses
> >> >>>
> >> >>> I would be happy if we could remove all three of this annoying  
> >> points.
> >> >> Exactly the same thought here. Also:
> >> >>
> >> >> int i = ...;
> >> >> char[] x = "You pressed button " + i;
> >> >>
> >> >> Oops... doesn't compile. To fix it:
> >> >>
> >> >> import std.string;
> >> >>
> >> >> int i = ...;
> >> >> char[] x = "You pressed button " + toString(i);
> >> >>
> >> >> But wait, if that piece of code is inside a method of a class, than
> >> >> (WHY?) it thinks it's the toString() method, so you end up writing:
> >> >>
> >> >> import std.string;
> >> >>
> >> >> int i = ...;
> >> >> char[] x = "You pressed button " + std.string.toString(i);
> >> >>
> >> >> Those are the cases I find D not nice.
> >> >
> >> > yarp i concur. phobos oughtta have a function asStr that converts  
> >> everything to string and concats. then you write:
> >> >
> >> > auto x = asStr("You pressed button ", i, " with your pinky toe");
> >> >
> >>
> >> This is also known as std.string.format.
> >
> > narp that interprets %s and shit which can quickly become dangerous.
> 
> No, unlike printf-family functions, writef/std.string.format and other D  
> counterparts *are* type-safe, so you can use %s with strings, ints, longs,  
> Objects, i.e. with just _anything_.

narp i meant something else. maybe dangerous was not the appropriate word. let's say surprising. 

import std.stdio, std.string;

void main()
{
    string shit = "I embed a %s thing";
    // ...
    writeln(format("innocent formatting string ", shit));
}

this will fail dynamically. the problem is that any string argument is searched for %. that bad behavior was fixed in writefln but not in string.format. writefln only parses its first string for % shit but not the others. as it should.

> > you'd have to say
> >
> > auto x = format("", ........);
> >
> 
> class Dude {}
> auto greeting = format("Hello, %s!", new Dude());

not sure what that illustrates but i also realize my fix was wrong. again all strings will be parsed for % shit. that blows.



More information about the Digitalmars-d mailing list