如何使用从指针到结构的relfect遍历嵌入式结构

时间:2017-09-11 11:47:50

标签: go

我有这段代码:

package main

import (
    "fmt"
    "reflect"
)

type B struct {
    X string
    Y string
}

type D struct {
    B
    Z string
}

func DeepFields(iface interface{}) []reflect.Value {
    fields := make([]reflect.Value, 0)
    ifv := reflect.ValueOf(iface)
    ift := reflect.TypeOf(iface)

    for i := 0; i < ift.NumField(); i++ {
        v := ifv.Field(i)

        switch v.Kind() {
        case reflect.Struct:
            fields = append(fields, DeepFields(v.Interface())...)
        default:
            fields = append(fields, v)
        }
    }

    return fields
}

func main() {
    b := B{"this is X", "this is Y"}
    d := D{b, "this is Z"}
    // fmt.Printf("%#v\n", d)
    fmt.Println(DeepFields(d)) //works fine

    // fmt.Println(DeepFields(&d)) //but I need to pass pointer
}

去游乐场:https://play.golang.org/p/1NS29r46Al

我需要使用指针来执行此操作,请参阅第44行。

1 个答案:

答案 0 :(得分:0)

为了能够发送指针和值元素,您可以将其添加到DeepFields函数中:

if ift.Kind() == reflect.Ptr {
    ifv = ifv.Elem()
    ift = ift.Elem()
}

修改过的游乐场:https://play.golang.org/p/MgB-W81dYr