Okay, what happened to my literal strings?

Kirk McDonald kirklin.mcdonald at gmail.com
Thu Sep 6 13:31:33 PDT 2007


Burton Radons wrote:
> So I just installed DMD 2.004 (I thought I had a DMD 2.0 version already 
> installed), and now, no matter which DMD 2.0 I install (removing the dmd 
> and dm directories first), this code fails:
> 
> 'char [] foo = "bar";'
> 
> With the error code:
> 
> 'foo.d(1): Error: cannot implicitly convert expression ("bar") of type 
> invariant char[3] to char[]'.
> 
> The only difference between the versions is that DMD 2.002 and up say 
> "char[3u]" in the error message instead of "char[3]". All literal 
> strings fail with this error message. The latest DMD 1.0 works fine, but 
> I need traits.

You missed the word "invariant". String literals are of type 
invariant(char)[n] in D 2.x. (Where 'n' is the length of the string.) 
This is part of the new const semantics in 2.x.

You have two options: Either explicitly .dup the string literal, placing 
a mutable copy on the heap:

char[] foo = "bar".dup;

Or use the 'string' alias to use the immutable string literal directly:

string foo = "bar";

'string' is an alias to const(char)[]. You can implicitly convert 
invariant types to const types. Using 'string' is highly recommended.

-- 
Kirk McDonald
http://kirkmcdonald.blogspot.com
Pyd: Connecting D and Python
http://pyd.dsource.org



More information about the Digitalmars-d mailing list