Golang: Converting a String to an Int64

The strconv package executes conversions to and from string representations of basic data types like int32, int64, float, etc.

What is an int64 in Go?

Data types from int store signed integers, and those from uint contain unsigned integers. A variable of type int64 can store integers ranging from -9223372036854775808 to **9223372036854775807.

Golang String to Int64

To convert a string to int64 in Golang, use the strconv.ParseInt() function. The ParseInt() function takes a string, an int base 10, and a bitSize 64 and returns an int64 value. The ParseInt() function interprets a string in the given base (0, 2 to 36) and bit size (0 to 64) and returns the corresponding value.

The bitSize argument sets an integer type into which the return result must fit.

package main

import (
  "fmt"
  "reflect"
  "strconv"
)

func main() {
  var str string = "9223372036853778789"
  it64, err := strconv.ParseInt(str, 10, 64)
  if err != nil {
    panic(err)
  }
  fmt.Printf("A %v has a type %s!\n", it64, reflect.TypeOf(it64))
}

Output

A 9223372036853778789 has a type int64!

In this example, we declared a string “9223372036853778789”.

Then, convert a string to int64 by passing the following three values to the strconv.ParseInt() function.

  1. string: “9223372036853778789
  2. base: 10
  3. bitSize: 64

If the ParseInt() function fails to convert to int64, it throws an error. Otherwise, it returns an int64 value.

To find a data type of variable in Golang, use the reflect.TypeOf() function.

Conclusion

The strconv.ParseInt() function returns an integer converted from an input string. Using ParseInt() function, we converted a string to an int64 data type value.

Leave a Comment