douyu3145 2013-06-20 18:10
浏览 217
已采纳

转到:在类型转换中将任何int值转换为int64

I often have a situation, where I expect an int (of any type, int/int8/16/32/64) and check for it using a type switch

switch t := v.(type) {
  case int, int8, int16, int32, int64:
    // cast to int64
  case uint, uint8, uint16, uint32, uint64:
    // cast to uint64
}

Now I cannot use a direct cast, because t in this case will be of type interface{}. Do I really have to split this up into cases for each integer type?

I know that I could do it via reflection using reflect.ValueOf(v).Int(), but shouldn't there be a better (less verbose) way of doing this?

UPDATE:

Filed an issue, and Rob advised to just use reflect in this case.

  • 写回答

4条回答 默认 最新

  • dongwo5940 2013-06-20 20:34
    关注

    It's hard to give you an opinion without more context but it looks like you're trying to make your implementation too generic, which is common from people that worked mostly with more dynamic languages or w/ generic support.

    Part of the process of Learning Go is learning to embrace its type system, and depending on where you're coming from, it can be challenging.

    Usually, in Go, you want to support one type that can hold all possible values you need to handle. In your case it would probably be a int64.

    Take a look on the math package, for example. It only work with int64 and expect anyone using it to typecast it properly instead of trying to convert everything.

    Another option is to use a interface to be type-agnostic, like the sort package does. Basically, any method that are type specific will be implemented outside of your package and you expect certain methods to be defined.

    It takes a while to learn and accept these attributes but overall, in the end, it proves to be good in terms of maintainability and robustness. Interfaces ensure you have orthogonality and strong types makes sure you're in control of type conversions, which in the end can cause bugs and also unnecessary copies in memory.

    Cheers

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序
  • ¥15 onvif+openssl,vs2022编译openssl64
  • ¥15 iOS 自定义输入法-第三方输入法
  • ¥15 很想要一个很好的答案或提示
  • ¥15 扫描项目中发现AndroidOS.Agent、Android/SmsThief.LI!tr
  • ¥15 怀疑手机被监控,请问怎么解决和防止
  • ¥15 Qt下使用tcp获取数据的详细操作