1
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())
    }
}

我正在尝试将这些结构转换为 map[string]string,因为我需要 map 来更新 mongoDB 查询。将我的结构转换为 BSON 后,而不是查询 { "pet.name": "Groot" } 它变成 { "pet": { "name": "Groot" } } 删除嵌入文档宠物中的其他字段。我不确定如何覆盖 BSON 编组,因为我使用的是 mongodb 驱动程序,而不是 mgo

我想得到移动指针的值和宠物的名字,但我得到的只是地址

如何获得价值,例如 7777 和 Groot ?谢谢

4

1 回答 1

0

您可以使用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

例如,要在您的示例中检索手机号码,您应该将 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)
}
于 2020-11-08T17:49:04.027 回答