I'm looking for integer conversion functions resembling this:
func narrow(x int64) (int32, error) { ... }
In this example, the function would return ((int32)(x), nil)
if x
fits into an int32
, and (nil, someError)
if it doesn't.
There seem to be a lot of conversions built into the language, but they all silently swallow overflows, rather than providing a reified error. Am I missing something?
The conversions do not report overflow.
Here's a function that handles positive and negative numbers:
func narrow(x int64) (int32, error) {
y := int32(x)
if int64(y) != x {
return 0, errors.New("overflow")
}
return y, nil
}