struct initializer

Dennis dkorpel at gmail.com
Thu Nov 30 12:15:04 UTC 2023


On Thursday, 30 November 2023 at 07:21:29 UTC, Dom DiSc wrote:
> So, why supporting the (somewhat strange looking) version with 
> curly backets at all?
> It only works in one special place, so is simply overhead to 
> remember.
> Again a superfluous way to do the same - but only under 
> specific circumstances.
>
> I think a syntax should work either always or never.

The syntax was inherited from C. The 'special place' is called 
initialization, and it's special because the target type of the 
initializer is known in advance, while normal expression 
assignments are analyzed bottom up. Since there is no 
`typeof({10, 10})`, struct initializers don't work as expressions.

C99 added Compound literals `(S){.a = 10, .b = 20}`, and with 
named arguments you can do the same in D: `S(a: 10, b:20)`, and 
since the type name is included, they do work as standalone 
expressions.

Walter tried to deprecate the old struct initializer syntax:
https://github.com/dlang/DIPs/blob/master/DIPs/other/DIP1031.md

But it got some resistance, since {} initializers still have an 
advantage when you want to define an array of structs, and don't 
want to repeat the (potentially long) struct name for every entry.

Also note that even when {} is removed, there are still other 
special cases with initialization, for example with arrays:

```D
void main()
{
     short[] a = [3: 10]; // ok
     a = [3: 10]; // cannot implicitly convert expression `[3:10]` 
of type `int[int]` to `short[]`
}
```


More information about the Digitalmars-d-learn mailing list