Thread overview | ||||||
---|---|---|---|---|---|---|
|
June 02, 2019 Very simple null reference escape | ||||
---|---|---|---|---|
| ||||
A.B If A is null, crash. A?.B : writeln("HAHA"); No crash, ignored, equivalent to if (A is null) writeln("HAHA"); else A.B; |
June 02, 2019 Re: Very simple null reference escape | ||||
---|---|---|---|---|
| ||||
Posted in reply to Amex | On Sunday, 2 June 2019 at 07:55:27 UTC, Amex wrote: > A.B > > If A is null, crash. > > A?.B : writeln("HAHA"); > > No crash, ignored, equivalent to > > if (A is null) writeln("HAHA"); else A.B; The "optional" package on dub [1] has a .dispatch method that does this: auto d = some(A()); // Dispatch to one of its methods d.dispatch.f(); // calls a.f, returns some(4) d.dispatch.inner.g(); // calls a.inner.g, returns some(7) // Use on a pointer or reference type as well A* e = null; // If there's no value in the reference type, dispatching // works, and produces an optional assert(e.dispatch.f() == none); assert(e.dispatch.inner.g() == none); Full example: https://run.dlang.io/is/SmsGQu [1] https://code.dlang.org/packages/optional |
June 02, 2019 Re: Very simple null reference escape | ||||
---|---|---|---|---|
| ||||
Posted in reply to Paul Backus | On Sunday, 2 June 2019 at 14:37:48 UTC, Paul Backus wrote:
> On Sunday, 2 June 2019 at 07:55:27 UTC, Amex wrote:
>> A.B
>>
>> If A is null, crash.
>>
>> A?.B : writeln("HAHA");
>>
>> No crash, ignored, equivalent to
>>
>> if (A is null) writeln("HAHA"); else A.B;
>
> The "optional" package on dub [1] has a .dispatch method that does this:
>
> auto d = some(A());
>
> // Dispatch to one of its methods
>
> d.dispatch.f(); // calls a.f, returns some(4)
> d.dispatch.inner.g(); // calls a.inner.g, returns some(7)
>
> // Use on a pointer or reference type as well
> A* e = null;
>
> // If there's no value in the reference type, dispatching
> // works, and produces an optional
> assert(e.dispatch.f() == none);
> assert(e.dispatch.inner.g() == none);
>
>
> Full example: https://run.dlang.io/is/SmsGQu
>
> [1] https://code.dlang.org/packages/optional
thanks.
|
June 02, 2019 Re: Very simple null reference escape | ||||
---|---|---|---|---|
| ||||
Posted in reply to Amex | On Sunday, 2 June 2019 at 07:55:27 UTC, Amex wrote: > A.B > > If A is null, crash. > > A?.B : writeln("HAHA"); > > No crash, ignored, equivalent to > > if (A is null) writeln("HAHA"); else A.B; safeAccess from iz does this : https://github.com/Basile-z/iz/blob/master/import/iz/sugar.d#L1666 |
Copyright © 1999-2021 by the D Language Foundation