dongshui2254
dongshui2254
2019-05-28 15:34

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 dongzhi1949 2年前

    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

    点赞 评论 复制链接分享