How to get struct of function

156 views
Skip to first unread message

nakot...@gmail.com

unread,
Jul 26, 2016, 8:37:13 PM7/26/16
to golang-nuts
Lets say an example function like this

func (r *Router) Get(path string, controller interface{}) {}

And I am calling it this way

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



Refering to this function

type Test struct {
 
Name string
}


func
(t Test) IsWorking() {
 log
.Println("hello")
}

How can I get what struct is the function using? I mean on this example the struct would be Test and the function IsWorking... I have no idea how to achieve this

Running a reflect TypeOf to controller returns this

func(controllers.Test)

But I am not sure how to create a reflect.New of the type of controller.Test (without knowing about it)

Peter Waller

unread,
Jul 29, 2016, 5:26:46 AM7/29/16
to nakot...@gmail.com, golang-nuts
Try this:


--

package main

import (
"fmt"
"log"
"reflect"
)

func main() {
var controller interface{} = Test.IsWorking
funcTyp := reflect.TypeOf(controller)
structTyp := funcTyp.In(0)
newValue := reflect.New(structTyp).Interface()
fmt.Printf("%#+v", newValue)

Bruno Luis Panuto Silva

unread,
Aug 3, 2016, 9:19:52 AM8/3/16
to golang-nuts, nakot...@gmail.com
I suggest you also take a look at the Go spec that describes method values: https://golang.org/ref/spec#Method_values
It seems to click on what you want to do.
Also, take a look at this article from Alex Edwards: http://www.alexedwards.net/blog/organising-database-access more specifically, the "Dependency Injection" part. Look at how he takes the method booksIndex from a struct and is still able to reference to *Env in the handler.

Regards,
Bruno
Reply all
Reply to author
Forward
0 new messages