DIP 1031--Deprecate Brace-Style Struct Initializers--Community Review Round 1 Discussion

Steven Schveighoffer schveiguy at gmail.com
Fri Feb 14 16:39:06 UTC 2020


On 2/14/20 9:46 AM, Steven Schveighoffer wrote:
> You could even just keep the initializer syntax but with parentheses 
> instead of braces:
> 
> Foo f = Foo(ber: (a: 42, b: 84)); // only valid for struct 
> initialization without a ctor.
> 
> I think this would be unambiguous. But at that point, why are we even 
> deprecating the current syntax?

Hm... a possible benefit that has not been discussed, brace-style 
initialization is only allowed during initialization, because there are 
no types involved in the initialization expression.

But if we did the above, then the struct literal Foo(ber: (a: 42, b: 
84)) would be allowed in any expression, since the types for each 
parameter are unambiguous.

To recap:

1. We could make a struct literal syntax specifically for non-ctor 
structs that allows omission of types, since there are no overloads to 
worry about.
2. Such syntax would be valid wherever such a struct needs creation, 
including expressions.

examples:

struct S
{
    int x;
    int y;
}

struct P // to demonstrate ambiguity
{
    int y;
    int x;
}

struct NoCtor
{
    S s;
}

struct Ctor
{
    S s;
    this(S s) { this.s = s; }
    this(P s) { this.s = S(x: p.x, y: p.y); }
}

void foo(Ctor c);
void foo(NoCtor nc);

void main()
{
   S s = S(x: 1, y: 2); // given by this DIP
   NoCtor nc = NoCtor(s: (x: 1, y: 2)); // also OK, not a function call
   NoCtor nc2 = NoCtor((1, 2)); // also OK, no names required once 
inside struct literal without ctor
   Ctor c = Ctor(s: (x: 1, y: 2)); // Error, would be ambiguous
   Ctor c = Ctor(s: S(x: 1, y: 2)); // Must supply full expression for 
ctor param
   foo(Ctor(s: P(x: 1, y: 2)); // OK
   foo(NoCtor(s: (x: 1, y: 2))); // OK, not a ctor function
}

Essentially POD types get an upgrade for their static initialization 
syntax to be allowed in expressions.

-Steve


More information about the Digitalmars-d mailing list