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

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

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料