Right now I am doing the following in order to parse an integer from a string and then convert it to int
type:
tmpValue, _ := strconv.ParseInt(str, 10, 64) //returns int64
finalValue = int(tmpValue)
It is quite verbose, and definitely not pretty, since I haven't found a way to do the conversion in the ParseInt
call. Is there a nicer way to do that?
The parseInt function converts its first argument to a string, parses that string, then returns an integer or NaN . If not NaN , the return value will be the integer that is the first argument taken as a number in the specified radix .
One effective way to convert a string object into a numeral int is to use the stoi() function. This method is commonly used for newer versions of C++, with is being introduced with C++11. It takes as input a string value and returns as output the integer version of it.
It seems that the function strconv.Atoi
does what you want, except that it works regardless of the bit size of int
(your code seems to assume it's 64 bits wide).
If you have to write that once in your program than I see no problem. If you need at several places you can write a simple specialization wrapper, for example:
func parseInt(s string) (int, error) {
i, err := strconv.ParseInt(str, 10, 32) // or 64 on 64bit tip
return int(i), err
}
The standard library doesn't aim to supply (bloated) APIs for every possible numeric type and/or their combinations.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With