vendredi 14 avril 2017

Access pointer value of a struct inside a function

I want to pass a struct object to a function & be able to access its pointer value from that function. I am not able to understand why the following is resulting in error.

func GetStructFieldPointers(u interface{}, jsonFields []string) []interface{} {

    structVal := reflect.ValueOf(&u).Elem()
    structType := reflect.TypeOf(u)
    numberOfFields := structVal.NumField() // getting error here reflect: call of reflect.Value.NumField on interface Value
    numberOfJSONFields := len(jsonFields)
    res := make([]interface{}, numberOfJSONFields)
    fmt.Println(jsonFields)
    for fieldIndex, field := range jsonFields {
        for i := 0; i < numberOfFields; i++ {
            if structType.Field(i).Tag.Get("json") == field {
                valueField := structVal.Field(i)
                res[fieldIndex] = valueField.Addr().Interface()
            }
        }
    }

    return res

}

type User struct {
    Id             int      `json:"id"`
    Name           string   `json:"name"`
    Address        string   `json:"address"`
}
user := User{}
res := GetStructFieldPointers(user, []string{"id", "name"}) 

To make this work, I had to make structType as a parameter like following:

func GetStructFieldPointers(u interface{}, structType reflect.Type, jsonFields []string) []interface{} {

    structVal := reflect.ValueOf(u).Elem()
    // structType := reflect.TypeOf(u)
    numberOfFields := structVal.NumField() 
    numberOfJSONFields := len(jsonFields)
    res := make([]interface{}, numberOfJSONFields)
    fmt.Println(jsonFields)
    for fieldIndex, field := range jsonFields {
        for i := 0; i < numberOfFields; i++ {
            if structType.Field(i).Tag.Get("json") == field {
                valueField := structVal.Field(i)
                res[fieldIndex] = valueField.Addr().Interface()
            }
        }
    }

    return res

}
user := User{}
res := GetStructFieldPointers(&user, reflect.TypeOf(user), []string{"id", "name"}) 

I like to know how to pass User{} as a parameter & use in both reflect.ValueOf & reflect.TypeOf calls.

Thank you!





Aucun commentaire:

Enregistrer un commentaire