user3396016
user3396016

Reputation: 119

How can I invoke a variable method on a struct

I want to invoke a variable method on a struct like this example

type controller struct{}

func (c *controller) Index() {
    fmt.Println("index controller")
}

func invokeIt(action string) {
   (&controller{}).action    // don't work duh
   (&controller{})["action"] // this is Go not js
   // how can I invoke it? 
}

thx for the replies.

Upvotes: 0

Views: 83

Answers (1)

Ainar-G
Ainar-G

Reputation: 36189

DHH, are you porting Rails to Go :) ?

Jokes aside, this is exactly what reflect is for. For example:

type Foo struct{}

func (Foo) FooM() { fmt.Println("Foom") }

func main() {
    foo := Foo{}
    reflect.ValueOf(foo).MethodByName("FooM").Call(nil)
}

Playground: http://play.golang.org/p/5ZGwlHLEmj

EDIT: A more idiomatic way to do it would be to use interfaces, (as someone else had proposed, but then have deleted their answer). So if you want to, say, define something that can do CRUD, in Go you'd usually go with

type Resources interface {
    Index()
    New()
    Show(id int)
    // ...
}

And maybe an Invoke method in order to invoke non-standard methods on this thing using reflect like above. reflect is very powerful and also a good way to shoot yourself in the foot, so it's never a good idea to overuse it.

Upvotes: 4

Related Questions