我编写的代码根据其类型填充数据结构。如果存在,我需要调用嵌套结构函数。为什么当字段正确时我在寻找函数时得到零值?type ( SomeData struct { Val NestedType } NestedType struct { V1 string })func (t *NestedType) FillData(v int) { t.V1 = fmt.Sprintf("Here is %v", v)}func main() { i := SomeData{} reflect.ValueOf(&i.Val).MethodByName("FillData").Call([]reflect.Value{reflect.ValueOf(555)}) fmt.Println(i) /// {{I hate 555}} // BUT! v := 666 newObj := reflect.New(reflect.TypeOf(SomeData{})) fVal := newObj.Elem().FieldByName("Val") fmt.Println( "fVal.NumField():", fVal.NumField()) //fVal.NumField(): 1 f := fVal.MethodByName("FillData") f.Call([]reflect.Value{reflect.ValueOf(v)}) //panic: reflect: call of reflect.Value.Call on zero Value}
1 回答

白猪掌柜的
TA贡献1893条经验 获得超10个赞
- 1 回答
- 0 关注
- 265 浏览
添加回答
举报
0/150
提交
取消