dsedug8644 2016-09-20 20:15
浏览 505
已采纳

您如何从Go中的int转换溢出中得到错误?

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?

  • 写回答

1条回答 默认 最新

  • dongqian5384 2016-09-20 21:07
    关注

    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
    }
    

    playground example

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 树莓派安卓APK系统签名
  • ¥15 maple软件,用solve求反函数出现rootof,怎么办?
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波
  • ¥15 针对曲面部件的制孔路径规划,大家有什么思路吗