Char literals

Bill Baxter wbaxter at gmail.com
Fri Nov 6 06:49:08 PST 2009


On Fri, Nov 6, 2009 at 3:24 AM, Eldar Insafutdinov
<e.insafutdinov at gmail.com> wrote:
> I've just written a simple replicate function (the one from std.range does not work in CTFE):
> T[] replicate(T)(int n, T value)
> {
>    T[] ret;
>    if (n > 0)
>    {
>        for(int i = 0; i < n; i++)
>            ret ~= value;
>    }
>    return ret;
> }
> it's not the best implementation, but that's not the thing I want to say today. When I call it
>
> string str = replicate(5, 'a');
>
> I get
>
> moc.d(370): Error: cannot implicitly convert expression (replicate(5,',')) of type char[] to string
>
> That means that char literals are "char", but not "immutable(char)". I remember the whole conversation about array literals, but char literals are closer to those of the string. What's the reasoning behind leaving them as mutable char?

In Phobos they use std.contracts.assumeUnique to turn char[] to string
at the end of string processing functions.  It's actually just a cast
to immutable(char)[].  But the idea is you're asserting that you know
the char[] data is not referenced by anyone else (your reference is
unique) so it's safe to make it immutable.  So it documents the intent
better than a straight cast.  It's also better because if you later
change the underlying type say from char[] to dchar[], assumeUnique
will still do the right thing (become a cast to immutable(dchar)[]),
but cast(string) would silently become bogus.

--bb



More information about the Digitalmars-d mailing list