Why does struct initializer works for arrays but not for associative arrays?

Jonathan M Davis newsgroup.d at jmdavisprog.com
Wed Mar 14 15:17:54 UTC 2018


On Wednesday, March 14, 2018 13:36:51 Andre Pany via Digitalmars-d-learn 
wrote:
> Hi,
>
> I do not understand why struct initializer works for arrays but
> not for
> associative arrays:
>
> struct Bar
> {
>      string s;
> }
>
> struct Foo
> {
>      Bar[string] asso;
>      Bar[] arr;
> }
>
> void main()
> {
>      Foo foo = {
>          arr: [{s: "123"}],
>          asso: ["0": {s: "123"}] // does not work
>      };
> }
>
> The coding for both types of arrays looks very similiar:
> https://github.com/dlang/dmd/blob/9ed779a7d68d2ac489338cc4758c10d0cb169b39
> /src/dmd/initsem.d#L634
>
> I cannot spot the difference.
>
> Kind regards
> André

Well, I think that you have two issues here:

1. Struct literals work in only a few, specific circumstances. Why, I don't
know, but IIRC, someone was writing a DIP to fix that, and that may or may
not fix this case. So, as I understand it, it's not all that hard to run
into places where they don't work (I confess that I never use them, because
I don't like them any more than I like the fact that struct constructors are
implicitly declared if you don't declare them, which has caused me bugs when
changing the members fo a struct; both are misfeatures IMHO, though
obviously not everyone agrees on that point).

2. In general in D, the type of an expression is not inferred based on where
it's used. There are a few exceptions where literals are involved, but in
general, if you have something like

A a = expression;

expression has to evaluate correct on its own without taking A into account.
The fact that something like

Bar b = {s: "str"};

compiles is actually a bit of an oddity in D's semantics in that respect.
So, the fact that it works at all is a bit of a special case, and clearly,
they didn't get everything. My guess is that the problem is that the dynamic
array literal needs a type, but the compiler is not set up to figure out
what type that is based on the fact that it's being used in a struct
literal.

- Jonathan M Davis




More information about the Digitalmars-d-learn mailing list