tryTo: non-throwing variant of std.conv.to

Seb seb at wilzba.ch
Wed Aug 15 09:26:26 UTC 2018


On Wednesday, 15 August 2018 at 09:21:29 UTC, Per Nordlöw wrote:
> Have anybody thought about non-throwing variants of std.conv.to 
> typically named `tryTo`
> similar to what Folly
>
> https://github.com/facebook/folly/blob/master/folly/docs/Conv.md#non-throwing-interfaces
>
> does, for instance, as
>
>     tryTo<int>(str).then([](int i) { use(i); });
>
> ?
>
> Would it be sane to add these to std.conv alongside existing 
> std.conv.to so that underlying logic in std.conv.to can be 
> reused?
>
> If so, AFAICT, existing std.conv.to should be implemented on 
> top of std.conv.tryTo.

Well, for now you can use `ifThrown` from std.exception:

https://dlang.org/phobos/std_exception.html#ifThrown

---
"foo".to!int.ifThrown(42)
---

https://run.dlang.io/is/nlZKOw

Usage of optionals/nullables is sadly not very common in Phobos 
and I think if we want everything to work nicely, we probably 
have to start a new standard library (or do massive refactorings 
of the existing one.)


More information about the Digitalmars-d-learn mailing list