reflection - Golang 反射改进

标签 reflection go

有人知道更好的方法吗? 目标是将自定义字段从字符串再次转换回其 int 类型。

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))
   }

最佳答案

您可以使用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)
    }
}

playground

关于reflection - Golang 反射改进,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26275198/

相关文章:

c# - Java通过反射创建通用Arraylist

scala - 为什么ClassTag的runtimeClass方法返回一个通配符类?

java - 是什么导致了 java 泛型和反射的编译错误?

go - 如何保证一段代码执行不超过n次

c# - 动态 List<T>.Add 抛出 RuntimeBinderException

Golang本地导入

Go SDK Apache Beam : singleton side input Singleton for int ill-defined

amazon-web-services - Golang 中 AWS S3 中的 NoCredentialproviders

Go 模块替换命令不起作用

斯卡拉宏 : Add function to class