我有这个代码:
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
}
去 Playground :https://play.golang.org/p/1NS29r46Al
我需要使用指针来完成,请参阅第 44 行。
最佳答案
为了能够发送指针和值元素,您可以将其添加到您的 DeepFields
函数中:
if ift.Kind() == reflect.Ptr {
ifv = ifv.Elem()
ift = ift.Elem()
}
修改后的 Playground :https://play.golang.org/p/MgB-W81dYr
关于go - 如何使用从指向结构的指针反射来遍历嵌入式结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46155032/