反射struct中的struct得到<invalid reflect.Value>?

hahajie · · 1791 次点击
I got it myself. ``` package main import ( &#34;fmt&#34; &#34;os&#34; &#34;reflect&#34; &#34;text/template&#34; ) func getByKey(data interface{}, keys ...string) interface{} { defer func() { err := recover() if err != nil { fmt.Println(err) } }() for _, k := range keys { rdata := reflect.ValueOf(data) switch rdata.Kind() { case reflect.Map: mdata := data.(map[string]ZkNode) data = mdata[k] case reflect.Ptr: data = rdata.Elem().FieldByName(k).Interface() default: data = rdata.FieldByName(k).Interface() } } return data } type ZkNode struct { Value interface{} Key string Zz interface{} } func main() { data := make(map[string]ZkNode) data[&#34;test1&#34;] = ZkNode{ Value: &#34;123&#34;, Key: &#34;test1_key&#34;, } data[&#34;test2&#34;] = ZkNode{ Value: &#34;456&#34;, Key: &#34;test2_key&#34;, Zz: &amp;ZkNode{ Value: &#34;TF&#34;, Key: &#34;aaa&#34;, }, } tmplStr := ` begin {{D . &#34;test2&#34; &#34;Zz&#34; &#34;Value&#34; }} end ` tmpl, err := template.New(&#34;myt&#34;).Funcs(template.FuncMap{&#34;D&#34;: getByKey}).Parse(tmplStr) if err != nil { fmt.Println(err) } err = tmpl.Execute(os.Stdout, data) if err != nil { fmt.Println(err) } } ```
#1