First Draft: opUnwrapIfTrue

Juraj junk at vec4.xyz
Thu Feb 26 15:28:44 UTC 2026


On Thursday, 26 February 2026 at 13:53:41 UTC, Richard (Rikki) 
Andrew Cattermole wrote:
> The DIP: 
> https://gist.github.com/rikkimax/21242118e3bc1bf5f28024c2cdc33557
>
> A new operator overload to allow if statements to automatically 
> unwrap result types and ensure that the check is called prior 
> to, similar to foreach statements support of ranges.
>
> This solves a prolific issue that I have had to deal with 
> result types and has been exhibited by ``Nullable`` in PhobosV2.
>
> Full example:
>
> ```d
> import core.attribute : mustuse;
>
> @mustuse
> struct Result(Type) {
>     private {
>         Type value;
>         bool haveValue;
>     }
>
>     this(Type value) {
>         this.value = value;
>         this.haveValue = true;
>     }
>
>     bool opCast(T:bool)() => haveValue;
>
>     Type opUnwrapIfTrue() {
>         assert(haveValue);
>         return value;
>     }
> }
>
> Result!int result = Result!int(99);
>
> if (int value = result) {
>     // got a value!
>     assert(value == 99);
> } else {
>     // oh noes an error or default init state
> }
> ```


Feels like this will be hard to understand (I have to check 
`Result` for this op), I would much rather see movement on 
something like this:
<https://github.com/dlang/dmd/issues/20645>

Allowing this pattern:

```d
if (int value; result.tryGetValue(value)) {
   ...
}
```

IIRC, C++ has this feature as **if statements with initializer**


More information about the dip.development mailing list