dss087358 2016-07-26 19:47
浏览 48
已采纳

从函数类型获取结构

I currently have the following code

func (r *Router) Get(path string, controller interface{}) {
    ...
    t := reflect.TypeOf(controller)
    ...
}

That is called doing the following

Route.Get("/", controllers.Test.IsWorking)

The second argument is basically this

type Test struct {
    *Controller
    Name string
}

func (t Test) IsWorking() {

}

type Controller struct {
    Method   string
    Request  *http.Request
    Response http.ResponseWriter
    Data     map[interface{}]interface{}
}

I want to get the struct the function refers to. create a new struct of that type and call the function so for example

controllers.Test.IsWorking

Create a Test struct and call IsWorking()

  • 写回答

1条回答 默认 最新

  • doumowu7371 2016-07-26 19:57
    关注

    To make a new pointer to a newly allocated struct of the type in the interface, all you need is

    newController := reflect.New(reflect.TypeOf(controller)).Interface()
    

    Or to set a value on the new instance first:

    newController := reflect.New(reflect.TypeOf(controller))
    newController.Elem().FieldbyName("Method").Set(reflect.ValueOf("GET"))
    

    If you want to create a pointer to a struct and call the IsWorking method, it looks like

    t := reflect.New(reflect.TypeOf(Test{}))
    t.MethodByName("IsWorking").Call(nil)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办
  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)