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)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示