std.conv:to that does not throw?

Paul Backus snarwin at gmail.com
Thu Jan 30 16:23:02 UTC 2025


On Thursday, 30 January 2025 at 01:38:07 UTC, Kyle Ingraham wrote:
> Does D have a 'try' `std.conv:to` that does not throw if it 
> fails? Something like:
> ```D
> string input = "9";
> int output;
> auto parsed = input.tryTo!int(output);
> ```

You could try something like this:

```d
import std.typecons: Nullable, nullable;
import std.conv: to, ConvException;

Nullable!T tryTo(T, U)(U src)
{
     try
         return nullable(src.to!T);
     catch (ConvException e)
         return Nullable!T.init;
}

unittest
{
     assert("123".tryTo!int.get == 123);
     assert("hello".tryTo!int.empty);
}
```


More information about the Digitalmars-d-learn mailing list