Integer

Go Integer Data Types #

Integer data types are used to store whole numbers without decimals, such as 35, -50, or 1345000.

Go has two main categories of integers:

  1. Signed integers – can store both positive and negative values.
  2. Unsigned integers – can only store non-negative values.

Tip: The default integer type in Go is int. If you do not specify a type, the variable will be of type int.

Signed Integers #

Signed integers are declared using one of the int keywords. They can store both positive and negative values.

package main
import ("fmt")

func main() {
  var x int = 500
  var y int = -4500

  fmt.Printf("Type: %T, value: %v\n", x, x)
  fmt.Printf("Type: %T, value: %v\n", y, y)
}

Go Signed Integer Types #

TypeSizeRange
intDepends on platform: 32-bit or 64-bit-2,147,483,648 to 2,147,483,647 (32-bit), -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 (64-bit)
int88 bits / 1 byte-128 to 127
int1616 bits / 2 bytes-32,768 to 32,767
int3232 bits / 4 bytes-2,147,483,648 to 2,147,483,647
int6464 bits / 8 bytes-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807

Unsigned Integers #

Unsigned integers are declared using one of the uint keywords and can only store non-negative values.

package main
import ("fmt")

func main() {
  var x uint = 500
  var y uint = 4500

  fmt.Printf("Type: %T, value: %v\n", x, x)
  fmt.Printf("Type: %T, value: %v\n", y, y)
}

Go Unsigned Integer Types #

TypeSizeRange
uintDepends on platform: 32-bit or 64-bit0 to 4,294,967,295 (32-bit), 0 to 18,446,744,073,709,551,615 (64-bit)
uint88 bits / 1 byte0 to 255
uint1616 bits / 2 bytes0 to 65,535
uint3232 bits / 4 bytes0 to 4,294,967,295
uint6464 bits / 8 bytes0 to 18,446,744,073,709,551,615

Choosing the Right Integer Type #

The choice of integer type depends on the values your variable needs to store. Using a type with a smaller range than the value can cause an error.

package main
import ("fmt")

func main() {
  var x int8 = 1000
  fmt.Printf("Type: %T, value: %v\n", x, x)
}

Result:

./prog.go:5:7: constant 1000 overflows int8

Always select an integer type that can safely hold the expected range of values.