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 不小心不正规的开发公司导致不给我们y码,
  • ¥15 我的代码无法在vc++中运行呀,错误很多
  • ¥50 求一个win系统下运行的可自动抓取arm64架构deb安装包和其依赖包的软件。
  • ¥60 fail to initialize keyboard hotkeys through kernel.0000000000
  • ¥30 ppOCRLabel导出识别结果失败
  • ¥15 Centos7 / PETGEM
  • ¥15 csmar数据进行spss描述性统计分析
  • ¥15 各位请问平行检验趋势图这样要怎么调整?说标准差差异太大了
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 wpf界面一直接收PLC给过来的信号,导致UI界面操作起来会卡顿