Go Integer Data Types
In Go, integer data types are used to store whole numbers without decimal points, such as 35, -50, or 1345000.
There are two main categories of integer types:
- Signed Integers: These can hold both positive and negative values.
- Unsigned Integers: These can hold only non-negative values (zero and positive numbers).
Tip: If you don’t explicitly specify an integer type, Go will default to using int.
Signed Integers in Go:
Signed integers are declared using one of the int types (int, int8, int16, int32, or int64). They are capable of storing both positive and negative whole numbers.
Example:
package main
import "fmt"
func main() {
var a int = 500 // Positive signed integer
var b int = -4500 // Negative signed integer
fmt.Printf("Type: %T, Value: %v\n", a, a)
fmt.Printf("Type: %T, Value: %v\n", b, b)
}
Unsigned Integers:
Unsigned integers are declared using one of the uint keywords and can only store non-negative values (zero or positive numbers). They are ideal when you're certain that a variable will never hold a negative value.Example:
package mainimport "fmt"
func main() {
var x uint = 500 // Unsigned integer with value 500
var y uint = 4500 // Unsigned integer with value 4500
fmt.Printf("Type: %T, Value: %v\n", x, x)
fmt.Printf("Type: %T, Value: %v\n", y, y)
}
Choosing the Right Integer Type
When selecting an integer type, it's important to consider the range of values it needs to store. Each integer type has a specific size and range, and assigning a value outside that range will cause a compilation error.
Example
- The following code will result in an error because int8 can only store values from -128 to 127, and 1000 exceeds that range:
package main
import ("fmt")
func main() {
var x int8 = 1000
fmt.Printf("Type: %T, value: %v", x, x)
}
Output:
./prog.go:5:7: constant 1000 overflows int8
Tip: Always choose an integer type that can safely hold the values you expect to assign to the variable.