Struct Initialization syntax

H. S. Teoh hsteoh at quickfur.ath.cx
Mon Jul 23 16:57:20 UTC 2018


On Mon, Jul 23, 2018 at 04:26:42PM +0000, Seb via Digitalmars-d wrote:
> tl;dr: the currently proposed syntax options are:
> ---
> struct S
> {
>     int a = 2, b = 4, c = 6;
> }
> void foo()
> {
>     bar(S({c: 10})); // Option 1
>     bar(S(c: 10));   // Option 2
>     bar(S{c: 10});   // Option 3
> }
> ---
> 
> So the struct-initialization DIP has been stalled for too long and I
> think it's time we finally get this story done.

+1.


> I personally prefer option 2, but this might be in conflict to named
> arguments which we hopefully see in the near future too.

Yeah.


> Hence, I'm leaning forward to proposing Option 1 as the recommended
> Option for the DIP (that's also what the PoC DMD PR implements).
> What's your take on this?
[...]

I don't like option 1 because it resembles anonymous function syntax and
AA initialization syntax, but is actually neither.

I'm on the fence about option 2 and option 3.

I actually prefer option 3 as being overtly special initialization
syntax that doesn't try to masquerade as something else.

But OTOH, option 2 has a lot going for it, given that today, S(x, y, z)
is the syntax for initializing struct fields in order, so one would
expect that S(p: x, q: y, r: z) ought to be a natural extension of the
syntax for specifying fields out-of-order (or with some fields omitted).

It's true that there's potential conflict with named arguments, but IMO
it's a mighty bad idea to name ctor parameters in a way that conflicts
with the struct fields.  Either your struct has a member named x, your
ctor uses parameter names that are different from x (thus avoiding the
confusion), or if your ctor also takes a parameter named x, in which
case one would expect that it would initialize the member x, as opposed
to a different member y.  To have a ctor take a parameter named x but
using it to initialize member y instead of member x, seems to be such a
horrible idea that it should not be a big deal for struct initialization
syntax to "conflict" with it.


T

-- 
If you want to solve a problem, you need to address its root cause, not just its symptoms. Otherwise it's like treating cancer with Tylenol...


More information about the Digitalmars-d mailing list