cannot implicitly convert char[] to string

cym13 via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Aug 15 04:45:44 PDT 2015


On Saturday, 15 August 2015 at 11:34:01 UTC, cym13 wrote:
> On Saturday, 15 August 2015 at 11:25:20 UTC, vladde wrote:
>> I made a PR to phobos where I modified `std.format.format`. 
>> https://github.com/D-Programming-Language/phobos/pull/3528
>>
>> However the auto builder fails, with the error message:
>>> runnable/test23.d(1219): Error: cannot implicitly convert 
>>> expression (format("s = %s", s)) of type char[] to string
>>
>> The line which fails is `p = std.string.format("s = %s", s);`
>>
>> I don't understand why I can't convert a char[] to string.
>
> I think it has to do with the fact that string is an alias to   
> immutable(char)[]   and you can't implicitely cast an immutable 
> to a regular variable.

I phrased it completely wrong, an example will be better :

     import std.stdio;

     void fun(immutable(int)[] i) {
         i.writeln();
     }

     void main() {
         int[] i = [42];
         fun(i);
     }

Will not compile because there is no certainty that fun() won't
change the array while the following will work

     import std.stdio;

     void fun(immutable(int)[] i) {
         i.writeln();
     }

     void main() {
         int[] i = [42];
         fun(i.dup);

         immutable(int)[] j = [42];
         fun(j);

         immutable(int[]) k = [42];
         fun(k);
     }



More information about the Digitalmars-d-learn mailing list