以下代码获取指向函数 hello
的指针并打印它:
package main
import "fmt"
type x struct {}
func (self *x) hello2(a int) {}
func hello(a int) {}
func main() {
f1 := hello
fmt.Printf("%+v\n", f1)
// f2 := hello2
// fmt.Printf("%+v\n", f2)
}
但是,如果我取消注释底部的部分,编译错误会说:
> ./junk.go:14: undefined: hello2
所以我尝试了:
i := &x{}
f2 := &i.hello2
fmt.Printf("%+v\n", f2)
...但是错误是:
> ./junk.go:15: method i.hello2 is not an expression, must be called
好的,所以也许我必须直接引用原始类型:
f2 := x.hello2
fmt.Printf("%+v\n", f2)
没有:
> ./junk.go:14: invalid method expression x.hello2 (needs pointer receiver: (*x).hello2)
> ./junk.go:14: x.hello2 undefined (type x has no method hello2)
这类作品:
i := &x{}
f2 := reflect.TypeOf(i).Method(0)
fmt.Printf("%+v\n", f2)
但是,生成的 f2
是一个 reflect.Method
,而不是函数指针。 :(
这里合适的语法是什么?
最佳答案
您可以使用方法表达式,它将返回一个将接收者作为第一个参数的函数。
f2 := (*x).hello2
fmt.Printf("%+v\n", f2)
f2(&x{}, 123)
否则,您可以将函数调用包装在接受 x
作为参数的函数中。
f2 := func(val *x) {
val.hello2(123)
}
或者关闭现有的 x
值。
val := &x{}
f2 := func() {
val.hello2(123)
}
关于go - 如何在 go 中获取指向类型化函数的函数指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15352089/