Steven Schveighoffer wrote:
On Fri, 06 Mar 2009 13:30:22 -0800, Andrei Alexandrescu wrote:
Burton Radons wrote:
Andrei Alexandrescu Wrote:
Burton Radons wrote:
A more accurate way would be for the string type to be "const (char)
[]", and for functions which retain strings that can't change to take
"invariant (char) []". That makes pretty good claims about the nature
of the string, but it would clearly result in lots of cast
management.
I use that all the time, it's a great idiom. What cast management
needs to be done? What I need to do is occasionally insert an .idup on
the client side because the callee wants a copy. So that's that.
So long as the object definition of string is "invariant (char) []", I
can't guarantee anything about the nature of the object because you
need to cast to "invariant (char) []" to be able to interface with any
API.
The good side is that when I changed it to be defined as "const (char)
[]" only one line of code made a squeak. That gives me solid actionable
information. If an API is declared as istring, then whatever you give
it must not ever change. If an API is declared as string, then whatever
happens in there, it won't change the data. Pretty good!
I have trouble following what you're saying. If what you're saying is
essentially that in char[] is a better parameter definition than string
for functions that don't need to escape their string argument, then yes,
you are entirely right.
So what I recommend is:
void foo(in char[] s); // foo looks at s, doesn't escape it
void bar(string s); // bar needs to save s
void baz(char[] s); // baz needs
to change s' contents
I think what Burton is saying is by annointing immutable(char)[] as the
type "string," you are essentially sending a message to developers that
all strings should be immutable, and all *string parameters* should be
declared immutable. What this does is force developers who want to deal
in const or mutable chars have to do lots of duplication or casting,
which either makes your code dog slow, or makes your code break const.
Evidence is how (at least in previous releases) anything in Phobos that
took an argument that was a utf8 string of characters used the parameter
type "string", making it very difficult to use when you don't have string
types. If you want to find a substring in a string, it makes no sense
that you first have to make the argument invariant. a substring function
isn't saving a pointer to that data.
I think the complaint is simply that string is defined as immutable(char)
[] and therefore is promoted as *the only* string type to use. Using
other forms (such as in char[] or const(char)[] or char[]) doesn't look
like the argument is a string, when the word "string" is already taken to
mean something else.
-Steve
I see. Phobos is being changed to accept in char[] instead of string
wherever applicable. As far as what the default "string" ought to be,
immutable(char)[] is the safest of the three so I think it should be that.
Andrei