Golang 反射 MethodByName()

我编写的代码根据其类型填充数据结构。如果存在,我需要调用嵌套结构函数。


为什么当字段正确时我在寻找函数时得到零值?


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



}


森林海
浏览 284回答 1
1回答

白猪掌柜的

该方法在指针接收器上。值为fVala NestedType。调用Value.Addr以获得*NestedType:    f := fVal.Addr().MethodByName("FillData")在操场上运行它。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go