你如何获得一个函数指针到一个类型化的函数?
问题描述:
下面的代码获取一个函数指针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 UE。在围棋函数调用和关闭
val := &x{}
f2 := func() {
val.hello2(123)
}
答
相关阅读:“走1.1函数调用”拉斯考克斯(涵盖GO1在细节太)。
https://docs.google.com/document/d/1bMwCey-gmqZVTpRax-ESeVuZGmjwbocYs1iHplK-cjo/pub
这是一个很好的答案! – 2016-08-20 00:17:42