Go Integer Data Types
Need a whole number with no decimal part, such as 35, -50 or 1345000? Integer types are built for that.
They come in two families:
- Signed integers - hold positive numbers as well as negative ones
- Unsigned integers - hold zero and positive numbers, never negative ones
Note: Leave out the type and Go falls back on int, which is the default for whole numbers.
Signed Integers
The int family of keywords declares signed integers, so these variables accept negative numbers as well as positive ones:
Example
Prompt
Declare two signed int variables (positive and negative). Print their type and value using Printf.
Output: Go program and captured output
main.go
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)
}
Unsigned Integers
The uint family of keywords declares unsigned integers, so these variables cannot hold negative numbers:
Example
Prompt
Declare two unsigned int variables. Print their type and value using Printf.
Output: Go program and captured output
main.go
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)
}
Which Integer Type to Use?
Let the values you expect to store guide your choice.
Each type only covers a certain range, and Go reports an error when a value falls outside it. Take int8: it covers -128 to 127, so 1000 will not fit.