duankeng9477 2014-10-09 09:41
浏览 31
已采纳

Golang反射改善

Anyone know a better way to do this? The goal is for a custom defined Field to be casted back again from a string to its int type.

switch val.Kind() {
    case reflect.Int:
            intID, err := strconv.ParseInt(id, 10, 0)
            if err != nil {
                    return err
            }
            val.Set(reflect.ValueOf(int(intID)))

    case reflect.Int8:
            intID, err := strconv.ParseInt(id, 10, 8)
            if err != nil {
                    return err
            }
            val.Set(reflect.ValueOf(int8(intID)))

    case reflect.Int16:
            intID, err := strconv.ParseInt(id, 10, 16)
            if err != nil {
                    return err
            }
            val.Set(reflect.ValueOf(int16(intID)))

    case reflect.Int32:
            intID, err := strconv.ParseInt(id, 10, 32)
            if err != nil {
                    return err
            }
            val.Set(reflect.ValueOf(int32(intID)))

    case reflect.Int64:
            intID, err := strconv.ParseInt(id, 10, 64)
            if err != nil {
                    return err
            }
            val.Set(reflect.ValueOf(intID))
   }
  • 写回答

1条回答 默认 最新

  • dongwuxie5112 2014-10-09 09:50
    关注

    You can use Value.SetInt / Value.SetUint:

    func setId(id string, v interface{}) {
        // error checking is left as an exercise
        val := reflect.ValueOf(v).Elem() // this will panic if v isn't a pointer
        switch val.Kind() {
        case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
            idn, _ := strconv.ParseInt(id, 10, 64)
            if val.OverflowInt(idn) {
                // handle large values
            }
            val.SetInt(idn)
        case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
            idn, _ := strconv.ParseUint(id, 10, 64)
            if val.OverflowUint(idn) {
                // handle large values
            }
            val.SetUint(idn)
        }
    }
    

    <kbd>playground</kbd>

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

报告相同问题?

悬赏问题

  • ¥15 CSS实现渐隐虚线边框
  • ¥15 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题