gpt4 book ai didi

go - 如何在结构上调用变量方法

转载 作者:IT王子 更新时间:2023-10-29 02:30:22 26 4
gpt4 key购买 nike

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

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?
}

感谢回复。

最佳答案

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

编辑:一种更惯用的方法是使用接口(interface)(正如其他人所建议的,但后来删除了他们的答案)。所以如果你想,比如说,定义一些可以做 CRUD 的东西,在 Go 中你通常会选择

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

也许还有一个 Invoke 方法,以便像上面那样使用 reflect 在这个东西上调用非标准方法。 reflect 非常强大,也是搬起石头砸自己脚的好方法,所以过度使用它绝不是一个好主意。

关于go - 如何在结构上调用变量方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24741125/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com