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 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)