gpt4 book ai didi

pointers - 如何使用golang将结构的方法作为参数传递给另一个函数

转载 作者:数据小太阳 更新时间:2023-10-29 03:37:34 25 4
gpt4 key购买 nike

对不起,我又发帖了。

在我提出问题之前,我已经阅读了解决方案。我认为这对我没有帮助,因为我的问题是如何将函数作为参数传递?我不想调用它。

我只是想把它传递给另一个我不能编辑(或者我不想编辑)的函数,我想用一个字符串变量来指向这个函数

funcName := "Go"
m.set(t.funcName)

我觉得这和这个问题不一样Call a Struct and its Method by name in Go?

例如

我有这样的功能:

type Context struct{}
type myclass struct{}
type Handler func (c *Context)

func (r *myclass) set(ch Handler) {

}

我可以这样使用:

type testclass struct {}
func (t *testclass) Go(c *Context){
println("Hello");
}

t := &testclass{}
m := &myclass{}
m.set(t.Go)

我的问题是

type testclass struct{}
func (t *testclass) Go(c *Context){
println("Hello");
}

t := &testclass{}
m := &myclass{}

funcName := "Go"
m.set(t.funcName)

有什么方法可以做到这一点?

反射(reflection)?还是什么?

如果不可能,还有其他方法吗?

谢谢

最佳答案

您可以使用 reflect 包按名称获取方法。这是一个函数,用于获取给定名称的 Handler:

func handlerByName(v interface{}, name string) (Handler, error) {
m := reflect.ValueOf(v).MethodByName(name)
if !m.IsValid() {
return nil, errors.New("method not found")
}
h, ok := m.Interface().(func(*Context))
if !ok {
return nil, errors.New("method is not a handler")
}
return h, nil
}

函数的使用方法如下:

h, err := handlerByName(t, "Go")
if err != nil {
// handle error
}
m.set(h)

playground example

请注意,handlerByName 返回的函数是原始函数的反射包装器(感谢@OneOfOne 指出这一点)。与直接调用函数相比,调用包装器的速度较慢。

关于pointers - 如何使用golang将结构的方法作为参数传递给另一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35836735/

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