Comment #0 by qs.il.paperinik — 2022-09-21T08:49:45Z
In Herb Sutter’s proposal for a brand new C++ syntax¹, I found this gem:
> “In this proposal, for(in auto x : rng) automatically
> is both efficient and guaranteed to be read-only.”
This is something D could do, too. Our `foreach` loops can be
foreach ( element; range) // copy
foreach ( ref element; range) // reference²
foreach (auto ref element; range) // copy/reference, depending on value category
foreach ( in element; range) // see next paragraph
foreach ( out element; range) // see next paragraph
`in` and `out` elements have the same binding as `in` and `out` function parameters. They bind to
opApply(int delegate(in Type));
and
opApply(int delegate(out Type));
respectively.
¹ https://raw.githubusercontent.com/hsutter/708/main/708.pdf
² That `ref` is effectively `auto ref` is a known bug.
Comment #1 by elpenguino+D — 2022-09-21T15:46:10Z
What is `out` supposed to be used for here? It seems like it'd be identical to `ref` in this context.
Comment #2 by qs.il.paperinik — 2022-09-22T13:03:51Z
(In reply to elpenguino+D from comment #1)
> What is `out` supposed to be used for here? It seems like it'd be identical
> to `ref` in this context.
An `out` parameter is not the same as a `ref` parameter. The difference is small, but it is there. You are not supposed to get information from an `out` parameter; instead, you’re supposed to assign to it. You may, of course, afterwards read the information you put in. `out` generally is primary documenting intent; if it were for the semantic differences alone, `ref` subsumes it.
Also note that, on loops, because of a bug, `ref` is a suggestion and reference semantics is not enforced. `out` would be new and enforcement of reference semantics would not break anyone’s code.
Comment #3 by qs.il.paperinik — 2023-02-22T14:13:04Z
(In reply to elpenguino+D from comment #1)
> What is `out` supposed to be used for here? It seems like it'd be identical
> to `ref` in this context.
In the simplest terms, you’re supposed to assign to an `out` variable. The D language does not enforce it, but e.g. C# does. D’s out is quite useless, it’s documenting intent more than anything. Besides that, you’re guaranteed that the object referred to is in its init state.
Comment #4 by robert.schadek — 2024-12-13T19:24:32Z