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 ansys fluent计算闪退
  • ¥15 有关wireshark抓包的问题
  • ¥15 需要写计算过程,不要写代码,求解答,数据都在图上
  • ¥15 向数据表用newid方式插入GUID问题
  • ¥15 multisim电路设计
  • ¥20 用keil,写代码解决两个问题,用库函数
  • ¥50 ID中开关量采样信号通道、以及程序流程的设计
  • ¥15 U-Mamba/nnunetv2固定随机数种子
  • ¥15 vba使用jmail发送邮件正文里面怎么加图片
  • ¥15 vb6.0如何向数据库中添加自动生成的字段数据。