使用反射递归迭代结构并设置字段

使用反射递归迭代结构并设置字段

php小编西瓜在本文中将介绍如何使用反射递归迭代结构并设置字段。反射是PHP中一种强大的特性,它允许我们在运行时获取并操作类、方法、属性等信息。递归迭代结构是一种常用的处理方式,它可以帮助我们遍历和操作复杂的数据结构。通过结合反射和递归迭代结构,我们可以轻松地获取并设置字段的值,从而实现更灵活、高效的编程。在接下来的内容中,我们将详细介绍这一过程,帮助读者更好地理解和应用这个技巧。

问题内容

我想构建使用反射设置结构体字段的程序。我让它适用于顶级字段,但我正在努力处理嵌套结构字段。如何迭代嵌套结构字段?

type Payload struct { Type string `json:"type"` SubItem *SubItem `json:"sub_item"` } type SubItem struct { Foo string `json:"foo"` } func main() { var payload Payload setValue(&payload, "type", "test1") setValue(&payload, "sub_item.foo", "test2") } func setValue(structPtr interface{}, key string, value string) { structValue := reflect.Indirect(reflect.ValueOf(structPtr)) for i, subkey := range strings.Split(key, ".") { isLast := i == len(strings.Split(key, "."))-1 var found bool // this line is crashing with "reflect: call of reflect.Value.NumField on zero Value" for i := 0; i 登录后复制