The maximum value for an int type in Go
How does one specify the maximum value representable for an unsigned
integer type?
I would like to know how to initialize min
in the loop below that iteratively computes min and max lengths from some structs.
var minLen uint = ???
var maxLen uint = 0
for _, thing := range sliceOfThings {
if minLen > thing.n { minLen = thing.n }
if maxLen < thing.n { maxLen = thing.n }
}
if minLen > maxLen {
// If there are no values, clamp min at 0 so that min <= max.
minLen = 0
}
so that the first time through the comparison, minLen >= n
.
https://groups.google.com/group/golang-nuts/msg/71c307e4d73024ce?pli=1
The germane part:
Since integer types use two's complement arithmetic, you can infer the min/max constant values for
int
anduint
. For example,const MaxUint = ^uint(0) const MinUint = 0 const MaxInt = int(MaxUint >> 1) const MinInt = -MaxInt - 1
As per @CarelZA's comment:
uint8 : 0 to 255
uint16 : 0 to 65535
uint32 : 0 to 4294967295
uint64 : 0 to 18446744073709551615
int8 : -128 to 127
int16 : -32768 to 32767
int32 : -2147483648 to 2147483647
int64 : -9223372036854775808 to 9223372036854775807
https://golang.org/ref/spec#Numeric_types for physical type limits.
The max values are defined in the math package so in your case: math.MaxUint32
Watch out as there is no overflow - incrementing past max causes wraparound.
I would use math
package for getting the maximal and minimal values for integers:
package main
import (
"fmt"
"math"
)
func main() {
// integer max
fmt.Printf("max int64 = %+v\n", math.MaxInt64)
fmt.Printf("max int32 = %+v\n", math.MaxInt32)
fmt.Printf("max int16 = %+v\n", math.MaxInt16)
// integer min
fmt.Printf("min int64 = %+v\n", math.MinInt64)
fmt.Printf("min int32 = %+v\n", math.MinInt32)
fmt.Printf("max float64 = %+v\n", math.MaxFloat64)
fmt.Printf("max float32 = %+v\n", math.MaxFloat32)
// etc you can see more int the `math`package
}
Output:
max int64 = 9223372036854775807
max int32 = 2147483647
max int16 = 32767
min int64 = -9223372036854775808
min int32 = -2147483648
max float64 = 1.7976931348623157e+308
max float32 = 3.4028234663852886e+38