cannot initalize a struct for AA

Jonathan M Davis newsgroup.d at jmdavisprog.com
Sat Dec 15 02:40:41 UTC 2018


On Friday, December 14, 2018 7:22:51 PM MST Michelle Long via Digitalmars-d 
wrote:
> AA[key] = {a,b,c};
>
> fails.
>
> T a = {a,b,c};
> AA[key] = a;
>
> passes.
>
> The extra line is required simply to work, but there should be no
> difference semantically.

There is a difference. In the case of

T a = {a,b,c};

you're declaring a variable and explicitly initializing it. In the case of

AA[key] = {a,b,c};

you're assigning a value to a function which is using it to initialize a
value inside the AA. Yes, it's an overloaded function, but it's still not
semantically the same as initializing a variable. If anything, it's more
like an assignment than initialization, and basic assignment doesn't work
with that syntax either. e.g.

struct S
{
    int x;
    int y;
}

void main()
{
    S s;
    s = { 42, 19 };
}

will fail to compile. That particular syntax _only_ works with direct
initialization.

For better or worse, D does do some special stuff with direct initialization
that uses type inference that never gets used elsewhere (this particular
struct initialization syntax being one such example), but for most code, the
expression has to be known beforehand, so its type isn't inferred. This
includes assignment and function calls where the target type is known.

Now, there are folks who want to be able to do stuff like

foo({42, 19});

and have that work, and IIRC, someone was working on a DIP to allow that
sort of thing (which would presumably then include your use case), but as it
stands, that does not work. Instead, you can just use the normal constructor
syntax. e.g.

struct S
{
    int x;
    int y;
}

void main()
{
    S s;
    s = S(42, 19);
}

will work just fine, and the AA case will work as well. And for better or
worse, you don't even need to declare a constructor for a struct where you
just want to have the variables initialized without doing anything else in
the constructor. So, if you were using the {} syntax to avoid declaring a
constructor, that's unnecessary (though I've found that it's better practice
to just always declare a constructor and use it, because otherwise, you get
fun bugs if/when the struct gets changed later by having members added, or
if their order of declaration is changed).

- Jonathan M Davis





More information about the Digitalmars-d mailing list