Struct initializers as expressions

Marc Schütz via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Dec 4 07:08:24 PST 2015


On Friday, 4 December 2015 at 14:07:01 UTC, Jacob Carlborg wrote:
> On 2015-12-04 11:42, Marc Schütz wrote:
>
>> I'd support that, too.
>>
>> I suggest to make the struct name optional:
>>
>>      struct S { int a, b; }
>>      struct T { string a, b; }
>>      void foo(S s);
>>      void foo(T t);
>>
>>      foo({b: 1, a: 2});  // foo(S(2, 1));
>>      foo({a: "bla"});    // foo(T("bla", null));
>>
>> Then we can add some syntax sugar to leave out the braces, too:
>>
>>      void bar(int a, T t)
>>      bar(42, a: "bla", b: "xyz");
>>
>> This effectively gives us strongly typed named arguments, 
>> without making
>> the names part of the function signature, which Walter 
>> objected to the
>> last time something like this was proposed.
>
> I've been thinking along the same lines as well and would 
> really like to see that feature. Wondering if it could work 
> with opDispatch as well to swallow unrecognized fields.
>
> But I do see a problem, which I'm guessing Walter would point 
> out as well. It might/will complicate the overloading rules. 
> What if "a" and "b" in T would be integers instead. I think 
> that would be ambiguous.

Right, this would need to be rejected. When the compiler sees 
such syntax, it would need to get a list of struct types allowed 
in the current position, and try to construct each of them with 
the given arguments. If there isn't exactly one match, it is 
rejected. This way, there is no change to the overloading rules 
themselves, it's just a rule to determine the type of the {key: 
value, ...} expression. After that, overloading works as usual.


More information about the Digitalmars-d-learn mailing list