Home
Go
int Max (math.MaxInt)
Updated Jan 15, 2025
Dot Net Perls
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.
Math
Example. This program accesses the math package and uses constants. It even uses a constant within a loop, to iterate over all possible int32 values.
Part 1 The int type is often used in Go programs, and we can get its range by accessing math.MinInt and math.MaxInt.
Part 2 The uint8 type is often used by the alias byte. It has a max value of 255.
Part 3 As an unsigned type, uint will have a minimum of 0, but the maximum is very high.
Part 4 Here we show the minimum and maximum of the 32-bit integer type int32. This type has a sign bit so it can be negative.
Part 5 Perhaps the most useful way to use max and min constants is within loops, when we want to iterate over all possible numbers.
for
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
Summary. 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.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Jan 15, 2025 (new).
Home
Changes
© 2007-2025 Sam Allen