Implicit conversion of unique objects to mutable and immutable

Ali Çehreli acehreli at yahoo.com
Tue Jun 21 15:25:05 PDT 2011


(Note: I have a feeling that this must be related to the old 'unique' 
discussions, which I had somehow managed to stay out of. If so, I 
apologize for repeating an old story.)

It is most useful for a function to return the most mutable type unless 
there is good reason not to. Do you agree? foo() makes a fresh result and 
returns it:

char[] foo()
{
    char[] result;
    return result;
}

The caller can get the result as a char[] and modify it:

    char[] result = foo();
    result[0] = 'A';         // assume a valid element

But what if the caller wants to treat the returned value as immutable:

    string result = foo();

That's currently a compilation error: "Error: cannot implicitly convert 
expression (foo()) of type char[] to string"

When it makes sense, we have std.exception.assumeUnique() for the caller 
to use:

import std.exception;

// ...

    char[] result = foo();
    string immutable_result = assumeUnique(result);

But that's the wrong thing to do, as foo() may be changed in the future 
to return a non-unique result. I think the language should have the 
'unique' qualifier so that foo() could use it on the return type:

unique char[] foo()
{
    // ...
}

and the unique objects could be converted to immutable or mutable 
implicitly:

    string immutable_result = foo();   // fine
    char[] mutable_result = foo();     // fine too

Is this whole thing the same as that old 'unique' discussion? :)

But anyway... How do you solve the problem of deciding the return type of 
such functions?

Thank you,
Ali


More information about the Digitalmars-d-learn mailing list