string types: const(char)[] and cstring

Derek Parnell derek at psych.ward
Sat May 26 10:54:33 PDT 2007


On Fri, 25 May 2007 19:47:24 -0700, 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. 

We seem to have different experience. Most of the code I write deals with
changing strings - in other words, manipulating strings is very very common
in the sorts of programs I write.

> 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.

No it doesn't.

I have rarely seen 'string' used as a variable. In phobos it is used in
boxer.d and regexp.d only. I use it as an alias for 'char[]'. I see 'str'
used fairly often but not so much 'string'.

'cstring' is pronounced C-String which instantly brings to mind the
'string' implementation used by C language. Not something I imagine you
wish to imply.


> 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.

So 'const(char)[] x' means that I can change x.ptr and x.length but I
cannot change anything that x.ptr points to, right?

     void func(const(char)[] x)
     {
      x = "def"; // ok
      x.length = 0; // ok
      x[0] = 'd'; // fails
     }

And  'invariant(char)[] x' means that I cannot change x.ptr or x.length and
I cannot change anything that x.ptr points to, right?

     void func(invariant(char)[] x)
     {
      x = "def"; // fails
      x.length = 0; // fails
      x[0] = 'd'; // ok
     }

So what syntax is to be used so that x.ptr and x.length cannot be changed
but the characters referred to by 'x' can be changed?

     void func(char const([]) x) ???
     {
      x = "def"; // fails
      x.length = 0; // fails
      x[0] = 'd' // ok
     }

-- 
Derek Parnell
Melbourne, Australia
"Justice for David Hicks!"
skype: derek.j.parnell



More information about the Digitalmars-d-announce mailing list