Overflows don't seem to be part of the builtin packages in go.
What is the best way to test that you don't overflow when multiplying 2 integers ?
Something similar to Java Math.multiplyExact
...
Overflows don't seem to be part of the builtin packages in go.
What is the best way to test that you don't overflow when multiplying 2 integers ?
Something similar to Java Math.multiplyExact
...
It'd be possible for you to write your own multiplyExact
based on the suggestions on this thread:
https://groups.google.com/forum/#!msg/golang-nuts/h5oSN5t3Au4/KaNQREhZh0QJ
const mostNegative = -(mostPositive + 1)
const mostPositive = 1<<63 - 1
func multiplyExact(a, b int64) (int64, error) {
result := a * b
if a == 0 || b == 0 || a == 1 || b == 1 {
return result, nil
}
if a == mostNegative || b == mostNegative {
return result, fmt.Errorf("Overflow multiplying %v and %v", a, b)
}
if result/b != a {
return result, fmt.Errorf("Overflow multiplying %v and %v", a, b)
}
return result, nil
}
Playground: https://play.golang.org/p/V_TSC44VcPY