Search code examples
goreflect

How to use reflection to assign values to unknown structures


Structs may contains float32, int32, string or pointer to struct. Here is my code. But i do not know how to assign values to the structs inside.


type T struct {
    A int
    B string
    C *P
}

type P struct {
    A string
    B int
}

func main() {
    t := T{}
    decode(&t, []string{"99", "abc", "abc", "99"})
    fmt.Println(t)
}

Solution

  • You could do something like this:

    func decode(a interface{}, val []string) {
        rdecode(reflect.ValueOf(a).Elem(), val)
    }
    
    func rdecode(rv reflect.Value, val []string) int {
        var index int
        for i := 0; i < rv.NumField(); i++ {
            f := rv.Field(i)
    
            if f.Kind() == reflect.Ptr {
                if f.IsNil() {
                    f.Set(reflect.New(f.Type().Elem()))
                }
                f = f.Elem()
            }
    
            switch f.Kind() {
            case reflect.Int:
                tmp, _ := strconv.Atoi(val[index])
                f.Set(reflect.ValueOf(tmp))
                index++
            case reflect.String:
                f.SetString(val[index])
                index++
            case reflect.Struct:
                index += rdecode(f, val[index:])
            default:
                break
            }
        }
        return index
    }
    

    https://play.golang.com/p/Jyj0flzDBhu