string types: const(char)[] and cstring

Kirk McDonald kirklin.mcdonald at gmail.com
Sat May 26 17:07:25 PDT 2007


Marcin Kuszczak wrote:
> Derek Parnell 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.
>>
> 
> The same here. I don't have much experience with Java and really don't know
> why const strings are so usefull... 
> 
> Maybe someone could elaborate a little bit more?
> 

It might also be educational to look at Python, which also has immutable 
strings.

The first, and probably most important reason why strings are immutable 
in Python is so they can be used as hash keys. (Mutating an object being 
used as a hash key is bad, bad, bad.)

Other reasons are addressed here:
http://effbot.org/pyfaq/why-are-python-strings-immutable.htm

However, Python is a very different kind of language from D. Using 
strings as hash keys is extraordinarily important in Python, as the use 
of any identifier is in essence a hash lookup.

Providing immutable strings in D is very useful (so the compiler can 
enforce copy-on-write semantics, for instance), and I don't think anyone 
would dispute that. The issue seems to be whether the "default" string 
alias should be immutable. I would say, since D seems to subscribe to 
copy-on-write semantics, that it should be. And of course, if you need 
mutable strings, you will always be able to declare a char[].

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



More information about the Digitalmars-d-announce mailing list