gpt4 book ai didi

go - Go 允许算术运算溢出而不是抛出异常是预期的行为吗?

转载 作者:数据小太阳 更新时间:2023-10-29 03:42:53 28 4
gpt4 key购买 nike

我正在将一些 Go 代码移植到 Rust,我意识到 Rust 会在乘法期间发生溢出时发生 panic ,而 Go 允许发生溢出。

下面的测试代码,不会导致溢出但会打印减少的值。(测试通过:https://play.golang.org/)

func main() {
fmt.Println("test\n")
var key uint64 = 15000;

key = key*2862933555777941757 + 1

fmt.Println(key)
}

最佳答案

Spec: Integer overflow:

For unsigned integer values, the operations +, -, *, and << are computed modulo 2n, where n is the bit width of the unsigned integer's type. Loosely speaking, these unsigned integer operations discard high bits upon overflow, and programs may rely on "wrap around".

For signed integers, the operations +, -, *, /, and << may legally overflow and the resulting value exists and is deterministically defined by the signed integer representation, the operation, and its operands. Overflow does not cause a run-time panic. A compiler may not optimize code under the assumption that overflow does not occur. For instance, it may not assume that x < x + 1 is always true.

如上所述,存在溢出并且不会导致运行时 panic 。

但是一定要小心,就好像你有一个constant expressions ,因为它们具有任意精度,如果要将结果转换为不适合目标类型有效范围的固定精度,则会导致编译时错误。

例如:

const maxuint64 = 0xffffffffffffffff
var key uint64 = maxuint64 * maxuint64

fmt.Println(key)

以上结果:

constant 340282366920938463426481119284349108225 overflows uint64

maxuint64 * maxuint64是一个经过正确计算的常量表达式(其值为 340282366920938463426481119284349108225 ),但是当将此值分配给 keyuint64 类型的变量,它会导致编译时错误,因为此值不能由 uint64 类型的值表示.但这不是运行时 panic 。

查看相关问题:

Golang: on-purpose int overflow

Does Go compiler's evaluation differ for constant expression and other expression

How to store a big float64 in a string without overflow?

Proper way for casting uint16 to int16 in Go

关于go - Go 允许算术运算溢出而不是抛出异常是预期的行为吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56345629/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com