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:
- Signed integers – can store both positive and negative values.
- 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 typeint.
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 #
| Type | Size | Range |
|---|---|---|
| int | Depends 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) |
| int8 | 8 bits / 1 byte | -128 to 127 |
| int16 | 16 bits / 2 bytes | -32,768 to 32,767 |
| int32 | 32 bits / 4 bytes | -2,147,483,648 to 2,147,483,647 |
| int64 | 64 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 #
| Type | Size | Range |
|---|---|---|
| uint | Depends on platform: 32-bit or 64-bit | 0 to 4,294,967,295 (32-bit), 0 to 18,446,744,073,709,551,615 (64-bit) |
| uint8 | 8 bits / 1 byte | 0 to 255 |
| uint16 | 16 bits / 2 bytes | 0 to 65,535 |
| uint32 | 32 bits / 4 bytes | 0 to 4,294,967,295 |
| uint64 | 64 bits / 8 bytes | 0 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 int8Always select an integer type that can safely hold the expected range of values.