std.conv:to that does not throw?
Jonathan M Davis
newsgroup.d at jmdavisprog.com
Thu Jan 30 02:08:49 UTC 2025
On Wednesday, January 29, 2025 6:38:07 PM MST Kyle Ingraham via Digitalmars-d-learn 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);
> ```
>
> `std.conv:to` is super flexible and does exactly what I need.
> However, hitting an exception for conversion failures really
> slows down my code. A conversion failure wouldn't be an exception
> for my use case. I'm trying to write web application route
> constraint code like what's [available in
> C#](https://github.com/dotnet/aspnetcore/blob/main/src/Http/Routing/src/Constraints/IntRouteConstraint.cs#L53). There, code like `Int.TryParse` is used to figure out whether a string meets a route constraint.
>
> `std.conv:to` is almost perfect with it's flexibility across
> types. I'm just hoping I've missed the version that doesn't throw.
Unfortunately, there isn't currently a function like std.conv.to which does
not throw. It's been suggested before, but it's never been implemented (and
would probably require quite a bit of refactoring if we want to avoid code
duplication). It's definitely on the todo list for the next major version of
Phobos, but we've never added such a function to the current version.
So, if you want to avoid having the conversion throw, you have to test the
value that you're converting first to make sure that the conversion won't
fail - e.g. something like all!isDigit(input) if you're converting a string
to an int.
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list