On 12/28/11 6:06 AM, Peter Alexander wrote:
string is immutable(char)[]
I rarely *ever* need an immutable string. What I usually need is
const(char)[]. I'd say 99%+ of the time I need only a const string.
This is quite irritating because "string" is the most convenient and
intuitive thing to type. I often get into situations where I've written
a function that takes a string, and then I can't call it because all I
have is a char[]. I could copy the char[] into a new string, but that's
expensive, and I'd rather I could just call the function.
I think it's telling that most Phobos functions use 'const(char)[]' or
'in char[]' instead of 'string' for their arguments. The ones that use
'string' are usually using it unnecessarily and should be fixed to use
const(char)[].
In an ideal world I'd much prefer if string was an alias for
const(char)[], but string literals were immutable(char)[]. It would
require a little more effort when dealing with concurrency, but that's a
price I would be willing to pay to make the string alias useful in
function parameters.
I'm afraid you're wrong here. The current setup is very good, and much
better than one in which "string" would be an alias for const(char)[].
The problem is escaping. A function that transitorily operates on a
string indeed does not care about the origin of the string, but storing
a string inside an object is a completely different deal. The setup
class Query
{
string name;
...
}
is safe, minimizes data copying, and never causes surprises to anyone
("I set the name of my query and a little later it's all messed up!").
So immutable(char)[] is the best choice for a correct string abstraction
compared against both char[] and const(char)[]. In fact it's in a way
good that const(char)[] takes longer to type, because it also carries
larger liabilities.
If you want to create a string out of a char[] or const(char)[], use
std.conv.to or the unsafe assumeUnique.
Andrei