Statically forbid string ~ size_t ?

bearophile bearophileHUGS at lycos.com
Thu Oct 13 14:07:32 PDT 2011


This comes from a thread in D.learn.

This is a small Python2 program:


from sys import argv
x = len(argv)
s = "hello"
s += x
print s


Python is strongly typed so it refuses to append an integer number to a string:

Traceback (most recent call last):
  File "...\test.py", line 4, in <module>
    s += x
TypeError: cannot concatenate 'str' and 'int' objects


In Java if you append an integer number to a string the integer number gets first converted to a string:


class Main {
    public static void main(String[] args) {
        int x = args.length;
        String s = "hello";
        s += x;
        System.out.println(s);
    }
}


That Java code outputs:

hello0


Both Java and Python are far more commonly known than D, and they shape programmers expectations a bit.

This D2 code compiles and runs with DMD 2.056head:


void main(string[] args) {
    int x = args.length;
    string s = "hello";
    s ~= x;
}



(In this case Python2 is typed more strongly than D.)

I think that int+char is acceptable in D, but string~size_t is not good. I think this is bug prone (especially given the expectations of programmers coming from other languages). So I suggest to statically disallow string~size_t. string~char, string~dchar, and string~string are of course OK.

So far I have written no enhancement request/bug report on this because I am not so sure...

Bye,
bearophile


More information about the Digitalmars-d mailing list