如何为无符号整数类型指定可表示的最大值?
我想知道如何在下面的循环中初始化min,迭代计算一些结构的min和max长度。
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
}
使第一次通过比较,minLen >= n。
Go-1.17现在在数学包中定义了MaxInt, MaxInt和MinInt常量。
package main
import "fmt"
import "math"
const maxUint = uint(math.MaxUint)
func main() {
fmt.Println("Integer range on your system")
// .Println("MaxUint:", math.MaxUint) ERROR constant 18446744073709551615 overflows int
fmt.Println("MaxUint:", maxUint)
fmt.Println("MinInt:", math.MinInt)
fmt.Println("MaxInt:", math.MaxInt)
}
测试上面的代码:https://play.golang.org/p/5R2iPasn6OZ
来自Go 1.17发布说明:https://golang.org/doc/go1.17#math
数学包现在又定义了三个常量:MaxInt、MaxInt和MinInt。
对于32位系统,它们的值分别是2^32 - 1,2 ^31 - 1和-2^31。
对于64位系统,它们的值分别是2^64 - 1,2 ^63 - 1和-2^63。
提交:https://github.com/golang/go/commit/e8eb1d82
文档:https://pkg.go.dev/math pkg-constants
const (
MaxInt = 1<<(intSize-1) - 1 // New
MinInt = -1 << (intSize - 1) // New
MaxInt8 = 1<<7 - 1
MinInt8 = -1 << 7
MaxInt16 = 1<<15 - 1
MinInt16 = -1 << 15
MaxInt32 = 1<<31 - 1
MinInt32 = -1 << 31
MaxInt64 = 1<<63 - 1
MinInt64 = -1 << 63
MaxUint = 1<<intSize - 1 // New
MaxUint8 = 1<<8 - 1
MaxUint16 = 1<<16 - 1
MaxUint32 = 1<<32 - 1
MaxUint64 = 1<<64 - 1
)
参见Go源代码:https://github.com/golang/go/blob/master/src/math/const.go#L39