First Draft: opUnwrapIfTrue
Richard (Rikki) Andrew Cattermole
richard at cattermole.co.nz
Thu Mar 12 19:53:35 UTC 2026
On 13/03/2026 3:18 AM, Ogion wrote:
> 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)
DIP1053 did not provide this "TupleDeclarator".
Right now that isn't a thing.
I'm inclined to say that with ``opUnwrapIfTrue`` it could return a
tuple, that then is supported in the condition. ``If`` statements in
grammar have their own rules for var declarations so some more work is
required for it to work.
More information about the dip.development
mailing list