optional assignment
Paul Backus
snarwin at gmail.com
Tue Dec 31 18:10:52 UTC 2024
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);
}
```
More information about the dip.ideas
mailing list