1

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\n")
    var key uint64 = 15000;

    key = key*2862933555777941757 + 1

    fmt.Println(key)
}
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Mazeryt
  • 855
  • 1
  • 18
  • 37
  • 1
    No, as you've proven yourself, it does not. Numbers are truncated at the boundary of the data type they're stored in. – Adrian May 28 '19 at 15:35

1 Answers1

13

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

icza
  • 389,944
  • 63
  • 907
  • 827
  • Thanks for the explanation! Really appreciate that! – Mazeryt May 28 '19 at 15:52
  • 1
    Might be worth noting that overflowing is perfectly fine in Rust as well if you compile for release rather than debug. There is [`u64::checked_mul()`](https://doc.rust-lang.org/std/primitive.u64.html#method.checked_mul) if that is not desired. – Fynn Becker May 29 '19 at 12:13