optional assignment

Quirin Schroll qs.il.paperinik at gmail.com
Wed Feb 5 12:20:33 UTC 2025


On Sunday, 2 February 2025 at 03:30:17 UTC, Walter Bright wrote:
> ```
> if (!a) a = b;
> ```
>
> Doesn't seem that bad. I did some searches and found hardly any 
> instances of it, though that was across the dmd sources.

Compare:
```d
int* _field = null; // lazy init

int getField1() => *(_field ??= new int(10));

int getField2()
{
     if (!_field)
     {
         _field = new int(10);
     }
     return *_field;
}
```

I see `get => list ??= new List();` and the like all the time in 
C# for lazy init containers. It’s a common pattern.

An `if` statement forces a body, forces braces with many linters, 
and (technically) requires evaluating the operand twice so it’s 
not even equivalent.

```d
int getField3()
{
     auto ref field = _field;
     if (!field)
     {
         field = new int(10);
     }
     return *field;
}
```
This is the actually equivalent code if


More information about the dip.ideas mailing list