First Draft: opUnwrapIfTrue
Paul Backus
snarwin at gmail.com
Thu Feb 26 16:01:22 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
The "Rationale" section begins as follows:
> In the authors codebase is a result type, with support for an
> error. It goes to an extreme extent to require a check for a
> given value of the result type to have been checked using
> `opCast!bool`, however this is very easy to miss when you do
> the `get` call which results in a runtime error. This was
> exhibited over many years period as being problematic.
This seems like an entirely self-inflicted problem. You've
designed an API that's a pain in the butt to use, and now you
want to add a language feature to compensate for your bad design.
A better solution would be to redesign your API to combine the
check and the access into a single operation, either with a
higher-order function like `Nullable`'s [`apply`][1], or with an
`opApply` overload:
```d
struct Result(T)
{
private T value;
private bool hasValue;
this(T value)
{
this.value = value;
this.hasValue = true;
}
int opApply(Body)(scope Body body)
{
if (this.hasValue)
return body(this.value);
return 0;
}
}
Result!int div(int n, int m)
{
if (m) return Result!int(n / m);
else return Result!int.init;
}
void main()
{
import std.stdio;
// prints 5
foreach (int result; div(10, 2))
writeln(result);
// prints nothing
foreach (int result; div(1, 0))
writeln(result);
}
```
[1]: https://dlang.org/phobos/std_typecons.html#apply
More information about the dip.development
mailing list