Int
Max
Suppose you are writing a Go program and want to know the maximum value of an int32
variable. This is a constant, and it is easily accessed from the math package.
After importing the math package, we can then access constants like math.MaxInt
and math.MaxInt32
. We may need to cast these constants to the desired type.
This program accesses the math package and uses constants. It even uses a constant within a loop, to iterate over all possible int32
values.
int
type is often used in Go programs, and we can get its range by accessing math.MinInt
and math.MaxInt
.byte
. It has a max value of 255.uint
will have a minimum of 0, but the maximum is very high.int32
. This type has a sign bit so it can be negative.package main import ( "fmt" "math" ) func main() { // Part 1: get min and max int values. m0 := math.MinInt m1 := math.MaxInt fmt.Println("INT MIN:", m0, "MAX:", m1) // Part 2: get max uint8 (also known as byte); the min is 0 as it is unsigned. m2 := math.MaxUint8 fmt.Println("BYTE MAX:", m2) // Part 3: get the max uint value with a cast. m3 := uint(math.MaxUint) fmt.Println("UINT MAX:", m3) // Part 4: get the min and max int32 values (32 bit signed integers). m4 := math.MinInt32 m5 := math.MaxInt32 fmt.Println("INT32 MIN:", m4, "MAX:", m5) // Part 5: use a range loop over all int32 values, and display one out of every 100 million numbers. for i := range math.MaxInt32 { if i % 100_000_000 == 0 { fmt.Println(i) } } }INT MIN: -9223372036854775808 MAX: 9223372036854775807 BYTE MAX: 255 UINT MAX: 18446744073709551615 INT32 MIN: -2147483648 MAX: 2147483647 0 100000000 200000000 300000000 400000000 500000000 600000000 700000000 800000000 900000000 1000000000 1100000000 1200000000 1300000000 1400000000 1500000000 1600000000 1700000000 1800000000 1900000000 2000000000 2100000000
In most languages, numeric types have a Max
or Min
constant property. But in Go we can access these values independently from the "math" package.