func overFlowTest() {
    maxInt32 := math.MaxInt32
    overflowedValue := maxInt32 + 1

    fmt.Println("Max Int32:", maxInt32)
    fmt.Println("Overflowed Value:", overflowedValue)
    fmt.Printf("Type of overflowedValue is %T\n", overflowedValue)
}

结果如下:

最大整数32:2147483647

溢出值:2147483648

overflowedValue的类型为int

当我try MaxInt64时,它溢出.这是否意味着当int32溢出时,它将自动转换为int64?

推荐答案

math.MaxInt32是一个无类型的常量:

const MaxInt32  = 1<<31 - 1           // 2147483647

如果在没有显式提供类型的情况下在short variable declaration中使用它:

maxInt32 := math.MaxInt32

将使用非类型化整数常量的默认类型,即int:

fmt.Printf("Type of maxInt32 is %T\n", maxInt32) // Prints int

Spec: Constants:

非类型化常量具有default type,这是在需要类型化值的上下文中将常量隐式转换为的类型,例如,在没有显式类型的short variable declaration(例如i := 0)中.无类型常量的默认类型分别为boolruneintfloat64complex128string,具体取决于它是布尔型、符号型、整型、浮点型、复数型还是字符串型常量.

int的大小取决于体系 struct ,在Go Playground上是64位的.因此,将1MaxInt32相加不会在64位整数中溢出.

如果将您的示例修改为使用int32类型:

maxInt32 := int32(math.MaxInt32)

输出将为(在Go Playground上试用):

Max Int32: 2147483647
Overflowed Value: -2147483648
Type of overflowedValue is int32
Type of maxInt32 is int32

推荐阅读量:The Go Blog: Constants

Go相关问答推荐

如何获得与cksum相同的CRC 32?

链自定义GRPC客户端拦截器/DialOptions

在Mac中使用uname获取处理器体系 struct 时,在为AMD64构建Go二进制时出现错误结果

Golang使用Run()执行的命令没有返回

使用Go使用Gorm使用外键对数据进行排序

埃拉托塞尼筛:加快交叉关闭倍数步骤

文件路径.Abs()未在结果中提供子目录

testcontainers:如何修复绑定源路径不存在

是否可以在 hyperledger-chaincode 中使用 gRPC?如果可以,我如何避免在测试网络上调用时出错?

我无法使用反向代理更改主机标头

致命错误 - 所有 Goroutines 都睡着了!僵局

Gorm delete with clauses sqlmock 测试

如何处理 Go 的 firebase admin sdk 错误?

确保 Go 1.20 编译时的严格可比性?

使用 AppID 在 Windows 中启动应用程序并获取 pid

io.Pipe 使用困难

try 与 golang testify/suite 并行运行测试失败

如何使用 math/big 对 bigInt 进行取模?

使用 oklog/run 来自 Go 编译器的错误(无值)用作值

如何在 docker 文件中安装 golang 包?