Go 反射(MethodByName)无效

Go 反射(MethodByName)无效,go,Go,MethodByName在反射时出现问题 代码: package main import ( "reflect" "fmt" ) type test struct {} var serviceType = map[string]reflect.Value{ "test": reflect.ValueOf(test{}), } func (t *test) prnt() { fmt.Println("test ok") } func callFunc(s

MethodByName在反射时出现问题

代码:

package main

import (
    "reflect"
    "fmt"
)

type test struct {}

var serviceType = map[string]reflect.Value{
    "test": reflect.ValueOf(test{}),
}

func (t *test) prnt()  {
    fmt.Println("test ok")
}

func callFunc(strct string, fName string)  {

    s := serviceType[strct].MethodByName(fName)
    if !s.IsValid(){
        fmt.Println("not correct")
        return
    }

    s.Call(make([]reflect.Value,0))
}

func main()  {
    callFunc("test", "prnt")
}
输出:

not correct
游乐场:


你能帮我一下吗,我做错了什么?

有两件事需要纠正

  • MethodByName()只返回导出的方法。因此,您必须重命名
    prnt
    tp
    prnt
  • 需要将struct
    test
    指针传递给
    reflect.ValueOf()
    方法

  • 这是修改后的工作代码

    非常感谢!