dongshui2254 2019-05-28 15:34
浏览 257
已采纳

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

I am porting some Go code to Rust and I realized that Rust panics when overflow occurs during multiplication while Go allows the overflow to happen.

Test code below, that does not cause overflow but print reduced value. (tested via: https://play.golang.org/)

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

    key = key*2862933555777941757 + 1

    fmt.Println(key)
}
  • 写回答

1条回答 默认 最新

  • dongzhi1949 2019-05-28 15:42
    关注

    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.

    As quoted above, overflow exists and it does not cause a run-time panic.

    But care must be taken, as if you have a constant expressions, since they have arbitrary precision, if the result is to be converted to a fixed precision where it does not fit into the target type's valid range, it results in a compile time-error.

    For example:

    const maxuint64 = 0xffffffffffffffff
    var key uint64 = maxuint64 * maxuint64
    
    fmt.Println(key)
    

    The above yields:

    constant 340282366920938463426481119284349108225 overflows uint64
    

    maxuint64 * maxuint64 is a constant expression which is properly calculated (its value is 340282366920938463426481119284349108225), but when this value is to be assigned to the key variable of type uint64, it results in a compile-time error because this value cannot be represented by a value of type uint64. But this is not a run-time panic.

    See related questions:

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误