Why doesn't std.variant.visit automatically call the provided delegates?
Kapps via Digitalmars-d
digitalmars-d at puremagic.com
Sat Nov 5 13:15:14 PDT 2016
On Saturday, 5 November 2016 at 10:09:55 UTC, Adam D. Ruppe wrote:
> On Saturday, 5 November 2016 at 08:27:49 UTC, Nemanja Boric
> wrote:
>> // This - does nothing
>> variant.visit!( (string s) => { enforce(false); x = 2;
>> },
>
> It calls the function... which returns a delegate, which you
> never called.
>
> This is one of the most common mistakes people are making: {}
> in D is a delegate, and () => is a delegate, therefore () => {}
> is a delegate that returns a delegate... usually NOT what you
> want.
>
> What you wrote is equivalent to writing
>
> delegate() callback(string s) {
> return delegate() {
> enforce(false);
> x = 2;
> };
> }
>
>
> Do not use the => syntax if there is more than one expression.
> You'll get what you want by simply leaving the => out:
>
>>
>> // This works as expected
>> variant.visit!( (string s) { x = 2; },
>> (int i) { x = 3; });
That's really confusing. I've used D for quite a while, and
didn't know that. Admittedly I doubt I've ever tried () => { },
but given languages like C# which this syntax was partially taken
from(?), that behaviour is very unexpected. That feels like it
should be a compiler warning.
More information about the Digitalmars-d
mailing list