D1 -> D2

Steven Schveighoffer schveiguy at yahoo.com
Thu Nov 18 12:30:53 PST 2010


On Thu, 18 Nov 2010 14:43:17 -0500, spir <denis.spir at gmail.com> wrote:

> On Thu, 18 Nov 2010 07:34:01 -0500
> "Steven Schveighoffer" <schveiguy at yahoo.com> wrote:
>
>> 4. if you intend on returning a portion of the string, well, currently
>> you're SOL, but eventually inout will come into play here.
>>
>> For example, Tango's log package fell under rules 1 and 3 (most of the
>> time you are creating log objects with string literals, and logging a
>> message does not save the message anywhere).
>> Many many cases fell under rule 4, which is one of the main reasons I  
>> gave
>> up (inout still isn't ready).
>
> I don't understand the issue here. Why don't slices do the job?

It's the source of the problem for which inout was invented to solve.  How  
do you specify a function that says "I won't molest the data" but returns  
a portion of that data?

Simplest example is strstr:

const(char)[] strstr(const(char)[] haystack, const(char)[] needle)

Notice that the return value *must* be const(char)[].  But what if you  
have a char[]?  All of a sudden, you can't modify that data which was  
returned to you.  In essence, strstr modified your const contract with  
your data.  The useful idiom:

str = strstr(str, "hello");

doesn't work, because you can't reassign the data.

A solution is to have 3 overloads, one for each constancy type, but the  
mutable version doesn't guarantee it won't modify the data, and you have  
to repeat the exact same code.  Another solution is to use a template, but  
that also has the same problem that it doesn't prevent the mutable version  
 from modifying the data, plus does not indicate that you can use const  
data.  In addition, templates cannot be virtual functions.

But inout solves this in a different way that does exactly what we want.   
If you have read TDPL, then it should explain how inout is *supposed* to  
work, or you can read DIP2  
(http://prowiki.org/wiki4d/wiki.cgi?LanguageDevel/DIPs/DIP2).  inout was  
chosen instead of vconst to allow reusing essentially a dead keyword.

-Steve


More information about the Digitalmars-d mailing list