std.conv:to that does not throw?

monkyyy crazymonkyyy at gmail.com
Thu Jan 30 02:52:49 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);
> ```
>
> `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.

its on my todo list for opend but isnt realisticly happening any 
time soon, I can suggest some patterns for setting up a cleaner 
`to` overloadset if you want to pick it up


More information about the Digitalmars-d-learn mailing list