Allow designated initialization of struct
IchorDev
zxinsworld at gmail.com
Sat Nov 2 17:54:24 UTC 2024
On Thursday, 12 September 2024 at 12:14:17 UTC, ryuukk_ wrote:
> Today i tried this:
>
>
> ```D
>
>
> struct Test
> {
> int test;
> }
>
> struct Data
> {
> Test[8] test;
> }
>
> void add(Data data)
> {
> }
>
> extern(C) void main()
> {
> add( Data(test: [ {test: 1}] ) );
> }
>
> ```
>
> it refuses to compile:
>
> ```
> onlineapp.d(19): Error: found `}` when expecting `;` following
> expression
> onlineapp.d(19): expression: `1`
> onlineapp.d(19): Error: found `]` instead of statement
> onlineapp.d(21): Error: found `End of File` when expecting `,`
> onlineapp.d(19): Error: found `End of File` when expecting `]`
> onlineapp.d(21): Error: found `End of File` when expecting `)`
> onlineapp.d(21): Error: found `End of File` when expecting `)`
> onlineapp.d(21): Error: found `End of File` when expecting `;`
> following expression
> onlineapp.d(19): expression: `add(Data(test: [()
> {
> test:
> 1;
> __error__
> }
> ]))`
> onlineapp.d(21): Error: matching `}` expected following
> compound statement, not `End of File`
> onlineapp.d(18): unmatched `{`
> ```
>
>
> D worse than C with these stupid RAII, give me proper way to
> initialize a struct instead of giving me a broken constructor
> i'm not even using
The [struct static initialiser
syntax](https://dlang.org/spec/struct.html#static_struct_init)
(using `{}`) is basically a barebones C-compatibility feature,
and it **only** works when **initialising a variable**. Stop
expecting it to have any sort of type-inference—Walter thinks
type-inference is The Devil! It would be nice if we did have type
inference, and my suggestion was writing the type name for a
constructor wouldn't be required if the type can be inferred from
its context (e.g. `add(%(test: [%(test: 1)])`), but doing this
for arrays is very messy because they infer their type from their
*contents*, not from where they're being sent. If we had the
aforementioned constructor type inference, then I wouldn't mind
even sending the static initialiser syntax to the deprecation
graveyard, even though I use it heavily in my libraries because
it predates named parameters.
More information about the dip.ideas
mailing list