I want to convert a string to an int64. What I find from the strconv
package is the Atoi
function. It seems to cast a string to an int and return it:
// Atoi is shorthand for ParseInt(s, 10, 0). func Atoi(s string) (i int, err error) { i64, err := ParseInt(s, 10, 0) return int(i64), err }
The ParseInt actually returns an int64:
func ParseInt(s string, base int, bitSize int) (i int64, err error){ //... }
So if I want to get an int64 from a string, should I avoid using Atoi, instead use ParseInt? Or is there an Atio64 hidden somewhere?
To convert a Double value to an Int64 value, use the Convert. ToInt64() method. Int64 represents a 64-bit signed integer.
Parsing string into int64 example:
// Use the max value for signed 64 integer. http://golang.org/pkg/builtin/#int64 var s string = "9223372036854775807" i, err := strconv.ParseInt(s, 10, 64) if err != nil { panic(err) } fmt.Printf("Hello, %v with type %s!\n", i, reflect.TypeOf(i))
output:
Hello, 9223372036854775807 with type int64!
https://play.golang.org/p/XOKkE6WWer
No, there's no Atoi64. You should also pass in the 64 as the last parameter to ParseInt, or it might not produce the expected value on a 32-bit system.
Adding abbreviated example:
var s string = "9223372036854775807" i, _ := strconv.ParseInt(s, 10, 64) fmt.Printf("val: %v ; type: %[1]T\n", i)
https://play.golang.org/p/FUC8QO0-lYn
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