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

转到:在类型转换中将任何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 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?