douxia3505 2017-04-14 07:09
浏览 23
已采纳

访问函数内部结构的指针值

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.

  • 写回答

1条回答 默认 最新

  • doulang9521 2017-04-14 07:47
    关注

    On this line: structVal := reflect.ValueOf(&u).Elem() you're taking the address of an interface (the argument of your func) and not an address to the interface's underlying value, and then you're passing the pointer to ValueOf, so the .Elem() call returns the "elem value" to which the pointer points to, which is the interface, not struct.

    If you know for a fact that the passed in value is a struct and not a pointer, all you need is this: structVal := reflect.ValueOf(u).

    If a pointer was passed to your func, eg GetStructFieldPointers(&u, ... then this is what you want: structVal := reflect.ValueOf(u).Elem().

    But also you can handle both cases by checking the value's kind.

    rv := reflect.ValueOf(u)
    if rv.Kind() == reflect.Ptr {
        rv = rv.Elem()
    }
    if rv.Kind() == reflect.Struct {
        fmt.Println(rv.NumField())
    }
    

    https://play.golang.org/p/9F9LNnwEaH

    Update: Took a better look at your code... If you want to be able to get the addresses of your struct's fields, you need to pass a pointer to the struct as the argument, or else those fields are going to be unaddressable.

    https://play.golang.org/p/RaA2rau3s-

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

报告相同问题?

悬赏问题

  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测