In Go, integer data types are used to represent numbers without decimal points, like 150, -72, or 100000.
Integer data types are classified into two main categories:
- Signed Integers
These integers can store both positive and negative values. - Unsigned Integers
These integers are restricted to storing only non-negative values.
Note: If you don’t specify an integer type explicitly, the default type is int
.
Signed Integers
Signed integers are declared using one of the int
keywords and can hold values that are either positive or negative.
Example: Declaring Signed Integers
package main
import ("fmt")
func main() {
var engineCapacity int = 1200 // Signed integer (positive)
var fuelEfficiency int = -20 // Signed integer (negative)
fmt.Printf("Type: %T, value: %v\n", engineCapacity, engineCapacity)
fmt.Printf("Type: %T, value: %v\n", fuelEfficiency, fuelEfficiency)
}
Output:
Type: int, value: 1200
Type: int, value: -20
Types of Signed Integers in Go
Type | Size | Range |
---|---|---|
int | Depends on platform: | -2147483648 to 2147483647 (32-bit systems) |
32-bit or 64-bit | -9223372036854775808 to 9223372036854775807 (64-bit systems) | |
int8 | 8 bits / 1 byte | -128 to 127 |
int16 | 16 bits / 2 bytes | -32768 to 32767 |
int32 | 32 bits / 4 bytes | -2147483648 to 2147483647 |
int64 | 64 bits / 8 bytes | -9223372036854775808 to 9223372036854775807 |
Unsigned Integers
Unsigned integers are declared using one of the uint
keywords and can store only non-negative values.
Example: Declaring Unsigned Integers
package main
import ("fmt")
func main() {
var bikePrice uint = 1500000 // Unsigned integer (positive only)
var insuranceFee uint = 25000 // Unsigned integer (positive only)
fmt.Printf("Type: %T, value: %v\n", bikePrice, bikePrice)
fmt.Printf("Type: %T, value: %v\n", insuranceFee, insuranceFee)
}
Output:
Type: uint, value: 1500000
Type: uint, value: 25000
Types of Unsigned Integers in Go
Type | Size | Range |
---|---|---|
uint | Depends on platform: | 0 to 4294967295 (32-bit systems) |
32-bit or 64-bit | 0 to 18446744073709551615 (64-bit systems) | |
uint8 | 8 bits / 1 byte | 0 to 255 |
uint16 | 16 bits / 2 bytes | 0 to 65535 |
uint32 | 32 bits / 4 bytes | 0 to 4294967295 |
uint64 | 64 bits / 8 bytes | 0 to 18446744073709551615 |
Choosing the Right Integer Type
When selecting an integer type, consider the range of values the variable will store.
Example of Incorrect Type Assignment
This example demonstrates an error caused by assigning a value beyond the range of int8
(valid range is -128 to 127):
package main
import ("fmt")
func main() {
var maxSpeed int8 = 300 // Out of range for int8
fmt.Printf("Type: %T, value: %v\n", maxSpeed, maxSpeed)
}
Result:
./prog.go:5:7: constant 300 overflows int8