On 02/22/2013 11:19 AM, Zane wrote:
> When is it appropriate to use in, out, inout, ref, immutable, and const
> in function parameters? I read the documentation and understand the
> basics behind them, but I'm a little confused, for example,

You are not alone. :)

> why someone would want to use 'out' instead of 'ref'

There is an idiom in C where a function first sets its "out parameter" to null (or another initial value) and then does some more work to fill that to actual result of the function:

int make_something(Something ** p)
{
    int err = 0;

    assert(p);
    *p = NULL;    // first, initialize

    // fill in p later on

    return err;
}

To me, 'out' of D does that initialization automatically.

> why 'in' instead of 'const',

'in' is nothing but 'const scope'. As scope is not implemented yet, in and const feel the same.

> or why 'immutable' instead of 'const'?

There is a very big semantic difference between those two:

const can take mutable, const, and immutable. In that sense, it is "welcoming."

immutable is demanding: It wants immutable perhaps because the immutable data will be stored for later use. An alternative for the function is to take const and then to make an immutable copy but that is sometimes wasteful.

If the function communicates its need to the caller, the caller hands over the immutable data, if the data is immutable to begin with. No copy needed in that case. Of course the caller may need to make an immutable copy from mutable data, but again, that copy is not wasted. Further, the caller may call assumeUnique to convert mutable data to immutable.

> If 'inout' is used as a wildcard,
> allowing for any of several storage classes, why is it needed at all
> (wouldn't 'ref' work?).

inout can transfer that information to the return type:

inout(Something) foo(inout(Something) parameter)
{
    // ...
}

> The more I think I get it, the more I end up
> getting confused. Am I thinking about this too hard? FYI: I come from
> primarily a C/Java/PHP background, so these concepts are relatively new
> to me - it feels excessive, though I am willing to learn.

I have tried to capture most of these concepts in the following chapters:

  http://ddili.org/ders/d.en/const_and_immutable.html

  http://ddili.org/ders/d.en/function_parameters.html

  http://ddili.org/ders/d.en/const_member_functions.html

Ali

--
D Programming Language Tutorial: http://ddili.org/ders/d.en/index.html

Reply via email to