optional assignment

Basile B. b2.temp at gmx.com
Sat Jan 4 20:16:14 UTC 2025


On Thursday, 2 January 2025 at 16:52:01 UTC, Basile B. wrote:
> On Tuesday, 31 December 2024 at 18:10:52 UTC, Paul Backus wrote:
>> On Monday, 30 December 2024 at 15:07:41 UTC, Basile B. wrote:
>>> A common pattern in a world where `null` exists is
>>>
>>> ```d
>>> if (!a)
>>>   a = b;
>>> ```
>>> [...]
>>>
>>> I propose the get rid of the statement layer. The two 
>>> statments (there are more actually) can be a single 
>>> expression:
>>>
>>> ```d
>>> a ?= b;
>>> ```
>>
>> ```d
>> ref optAssign(T, U)(ref T dest, U value)
>> {
>>     if (!dest) dest = value;
>>     return dest;
>> }
>>
>> unittest
>> {
>>     int n;
>>     int* p;
>>
>>     n.optAssign(123);
>>     assert(n == 123);
>>     n.optAssign(456);
>>     assert(n == 123);
>>
>>     p.optAssign(&n);
>>     assert(*p == 123);
>>     p.optAssign(new int(456));
>>     assert(*p == 123);
>> }
>> ```
>
> Paul while your template is somewhat equivalent, I have doubts 
> over people using it ;)
>
> The first problem I see is that it will be inline-ed only with 
> certains command line arguments, while the proposed expression 
> does not involved a call, or `-O`, or `-inline`.

Also people will have to import to make it available, while `?=` 
would just works, out of the box.


More information about the dip.ideas mailing list