Converting a String to an Integer
Summary
The ToInteger
trait should be implemented for String
, allowing one to convert a String
to an Integer
. This is similar to #134 (closed), which discusses adding support for converting a String
to a Float
.
Motivation
Converting strings into integers is a pretty common pattern, especially when writing parsers. Inko should provide this in the standard library, removing the need for third-party libraries.
Implementation
We will use Rust's str::parse::<i64>()
for this. Upon an overflow, Rust will return ParseIntError { kind: Overflow }
. Annoyingly, the kind
field appears private, and so does the enum (IntErrorKind
). There also do not seem to be any methods provided that can be used to detect generic parsing errors versus overflows. As a result, we'd basically have to take these steps:
- Try to parse the value as an
i64
- If this fails, try to parse it as a big integer (num-bigint implements the appropriate traits for this)
- If that also fails, panic or error
This also brings up the question: when the input is invalid, should we panic or throw? Since a method like this is bound to be used for user input, I'm inclined to say we should throw. However, I can see this being quite annoying to write: try! '123'.to_integer
. Then again, it is more flexible compared to a regular panic.
Drawbacks
None.