What is Golang’s int64 Type? Everything You Need to Know

Golang has an int data type for numeric values. An int data type will only store signed numeric values. Integers are like their mathematical counterpart numbers without a decimal component. Saving string value to an int variable returns an error.

Integers are platform-dependent because if you are on a 32-bit system, it will hold a signed int32 variable; if you are working on a 64-bit system, it will have a signed int64 variable.

Types of Ints in Golang

Go has the following type of integers.

  1. int8
  2. int16
  3. int32
  4. int64
  5. uint8
  6. uint16
  7. uint32
  8. uint64

Golang’s integer types are: int8, int16, int32, int64, uint8, uint16, uint32, and uint64.

The 8, 16, 32, and 64 tell us how many bits each type uses.

The uint means “unsigned integer”, while an int means “signed integer”. Unsigned integers only contain positive numbers (or zero).

In this tutorial, we will explicitly talk about the int64 type.

What is Golang int64?

Golang int64 is a 64-bit signed integer whose range is from -9223372036854775808 to 9223372036854775807. The int64 only stores signed numeric values composed of up to 64 bits.

How to create an int64 variable?

To create an int64 variable in Golang, use the var var_name int64 syntax.

package main

import (
  "fmt"
  "reflect"
)

func main() {
  var num int64 = 10
  fmt.Print(num, "\n")
  fmt.Print(reflect.TypeOf(num), "\n")
}

Output

10
int64

In this example, we created an int64 variable and printed its value and data type using the reflect.TypeOf() function.

We explicitly initialize a variable num with int64 type. Then, the num is stored as a variable of type int64.

While converting, you need to ensure that you don’t have a type that has a range lower than your current range; otherwise, you will lose your data.

Golang Integer Overflow

The integer overflow error in Golang may occur if you assign a type and then use a number larger than the types range to assign it.

package main

import (
  "fmt"
  "reflect"
)

func main() {
  var num int8 = 1000
  fmt.Print(num, "\n")
  fmt.Print(reflect.TypeOf(num), "\n")
}

Output

cannot use 1000 (untyped int constant) as int8 value in variable declaration (overflows)

To resolve the overflows error in Go, continually assign a type and use an integer compatible with that type.

Conclusion

Golang integers are either 32 or 64 bits, depending on the implementation. Usually, it’s int32 bits for 32-bit compilers and int64 bits for 64-bit compilers.

That’s it.

Leave a Comment