First Draft: opUnwrapIfTrue

Ogion ogion.art at gmail.com
Thu Mar 12 14:18:00 UTC 2026


On Thursday, 26 February 2026 at 13:53:41 UTC, Richard (Rikki) 
Andrew Cattermole wrote:
> 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.

We have a proposed tuple unpacking syntax[1] in this form:

```D
Tuple!int result = tuple(99);
(int value) = result;
assert(value == 99);

```

We could use the same syntax for unwrapping optional types. This 
requires some additional rules:
1. If the type has a boolean value, it is checked before 
unpacking. If the check fails:
1.1. If the unpacking declaration is in `if` statement, execution 
takes the `else` branch (if exists).
1.2. If the unpacking declaration is in `foreach` statement, 
execution continues to the next iteration.
1.3. Otherwise, an Error is thrown.

```D
@mustuse
struct Result(Type) {
     private {
         Type value;
         bool haveValue;
     }

     this(Type value) {
         this.value = value;
         this.haveValue = true;
     }

     bool opCast(T:bool)() => haveValue;

     (Type) = value; // TupleDeclarator (see DIP1053)
}

Result!int result = Result!int(99);
(int x) = result; // throws an Error if `result` is false.
if ((int y) = result) {
     assert(y == 99);
}
```

Looping over Results:
```D
foreach ((int x); getManyResults()) {
     writeln(x);
}
```

It Just Works™: Result that holds a tuple:
```D
Result!(Tuple!(int, string)) tupleResult = tuple(69, "nice");
if ((auto num, auto str) = tupleResult) {
     assert(num == 69);
     assert(str == "nice");
}
```


We could even apply the same syntax to pointers:

```D
int[string] map = ["key": 69];
if ((int value) = "key" in map) {
     assert(value == 69);
}

int*[] arr = getManyPointers();
foreach ((int x); arr) {
     writeln(x);
}
/* Same as:
foreach (p; arr) {
     if (p) {
         writeln(*p);
     }
}
*/

```

1\. 
https://github.com/dlang/DIPs/blob/master/DIPs/accepted/DIP1053.md


More information about the dip.development mailing list