Golang converting string to int64

Qian Chen picture Qian Chen · Feb 3, 2014 · Viewed 95.9k times · Source

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?

Answer

ET-CS picture ET-CS · Feb 1, 2015

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