简体   繁体   English

使用反射获取结构字段的指针值

[英]Get value of pointer of a struct field using reflect

package main

import (
    "fmt"
    "reflect"
)

type PetDetails struct {
    Name *string
}

type Student struct {
    Fname  string
    Lname  string
    City   string
    Mobile *int
    Pet *PetDetails
}

func main() {
    i := 7777777777
    petName := "Groot"
    s := Student{"Chetan", "Tulsyan", "Bangalore", &i, &PetDetails{&petName}}
    v := reflect.ValueOf(s)
    typeOfS := v.Type()
    
    for i := 0; i< v.NumField(); i++ {
        fmt.Printf("Field: %s\tValue: %v\n", typeOfS.Field(i).Name, v.Field(i).Interface())
    }
}

I am trying to convert these struct into map[string]string as I need the map for update query of mongoDB.我正在尝试将这些结构转换为 map[string]string,因为我需要用于 mongoDB 更新查询的映射。 After converting my struct to BSON, instead of querying { "pet.name": "Groot" } it becomes { "pet": { "name": "Groot" } } which deletes other fields inside the embedded document pet.将我的结构转换为 BSON 后,它不是查询 { "pet.name": "Groot" } 而是 { "pet": { "name": "Groot" } } ,它删除了嵌入文档 pet 中的其他字段。 I'm not sure how to override BSON marshals as I'm using mongodb driver, not mgo我不确定如何覆盖 BSON marshals,因为我使用的是 mongodb 驱动程序,而不是 mgo

I would like to get value of Mobile pointer and Name of the Pet, but all I get is the address我想获取移动指针的值和宠物的名称,但我得到的只是地址

How can I get the value, eg 7777 and Groot ?我如何获得价值,例如 7777 和 Groot ? Thanks谢谢

You can use Elem to dereference the pointer types.您可以使用Elem取消引用指针类型。

x := 5
ptr := reflect.ValueOf(&x)
value := ptr.Elem()

ptr.Type().Name() // *int
ptr.Type().Kind() // reflect.Ptr
ptr.Interface()   // [pointer to x]
ptr.Set(4)        // panic

value.Type().Name() // int
value.Type().Kind() // reflect.Int
value.Interface()   // 5
value.Set(4)        // this works

For example, to retrieve the mobile number in your example you should change the loop in main to:例如,要检索示例中的手机号码,您应该将 main 中的循环更改为:

for i := 0; i < v.NumField(); i++ {
    field := v.Field(i)
    value := field.Interface()

    // If a pointer type dereference with Elem
    if field.Kind() == reflect.Ptr {
        value = field.Elem().Interface()
    }

    fmt.Printf("Field: %s\tValue: %v\n", typeOfS.Field(i).Name, value)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM