string types: const(char)[] and cstring
Daniel Keep
daniel.keep.lists at gmail.com
Fri May 25 20:44:34 PDT 2007
Walter Bright wrote:
> Under the new const/invariant/final regime, what are strings going to be
> ? Experience with other languages suggest that strings should be
> immutable. To express an array of const chars, one would write:
>
> const(char)[]
>
> but while that's clear, it doesn't just flow off the keyboard. Strings
> are so common this needs an alias, so:
>
> alias const(char)[] cstring;
>
> Why cstring? Because 'string' appears as both a module name and a common
> variable name. cstring also implies wstring for wchar strings, and
> dstring for dchars.
>
> String literals, on the other hand, will be invariant (which means they
> can be stuffed into read-only memory). So,
> typeof("abc")
> will be:
> invariant(char)[3]
>
> Invariants can be implicitly cast to const.
>
> In my playing around with source code, using cstring's seems to work out
> rather nicely.
>
> So, why not alias cstring to invariant(char)[] ? That way strings really
> would be immutable. The reason is that mutables cannot be implicitly
> cast to invariant, meaning that there'd be a lot of casts in the code.
> Casts are a sledgehammer, and a coding style that requires too many
> casts is a bad coding style.
Thanks for the update; I'm happy to have const strings, and use char[]
manually when I want to mutate something.
One question though: are the parens necessary? I was under the
impression that const and invariant applied to reference types, so it
would be const char[] or const(char[]), since char by itself is just a
value type.
...this is going to turn into one of those mega threads where we all run
around in circles trying to work out which one is which, isn't it?
-- Daniel
--
int getRandomNumber()
{
return 4; // chosen by fair dice roll.
// guaranteed to be random.
}
http://xkcd.com/
v2sw5+8Yhw5ln4+5pr6OFPma8u6+7Lw4Tm6+7l6+7D
i28a2Xs3MSr2e4/6+7t4TNSMb6HTOp5en5g6RAHCP http://hackerkey.com/
More information about the Digitalmars-d-announce
mailing list