如何在结构体上调用一个变量方法?

huangapple go评论154阅读模式
英文:

How can I invoke a variable method on a struct

问题

我想在一个结构体上调用一个变量方法,就像这个例子一样:

type controller struct{}

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

func invokeIt(action string) {
   (&controller{}).action    // 这样不起作用
   (&controller{})["action"] // 这是Go不是js
   // 我该如何调用它?
}

谢谢回复。

英文:

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.

答案1

得分: 4

DHH,你是在将Rails移植到Go吗 :)?

开玩笑的,这正是reflect的用途。例如:

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

**编辑:**更符合惯用方式的方法是使用接口(正如其他人提出的,但他们已经删除了他们的答案)。所以,如果你想定义一个可以执行CRUD操作的东西,在Go中通常会这样做:

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

然后,可以使用类似上面使用reflect的方式来调用这个东西上的非标准方法,也可以在这个东西上定义一个Invoke方法。reflect非常强大,但也容易踩坑,所以过度使用它是不明智的。

英文:

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.

huangapple
  • 本文由 发表于 2014年7月15日 00:20:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/24741125.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定