Dou*_*oug 5 member-function-pointers function-pointers go
以下代码获取指向该函数的指针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)
}
Run Code Online (Sandbox Code Playgroud)
但是,如果我取消评论底部的部分,编译错误,说:
> ./junk.go:14: undefined: hello2
Run Code Online (Sandbox Code Playgroud)
所以我尝试过:
i := &x{}
f2 := &i.hello2
fmt.Printf("%+v\n", f2)
Run Code Online (Sandbox Code Playgroud)
...但错误:
> ./junk.go:15: method i.hello2 is not an expression, must be called
Run Code Online (Sandbox Code Playgroud)
好吧,也许我必须直接参考原始类型:
f2 := x.hello2
fmt.Printf("%+v\n", f2)
Run Code Online (Sandbox Code Playgroud)
不:
> ./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)
Run Code Online (Sandbox Code Playgroud)
这种作品:
i := &x{}
f2 := reflect.TypeOf(i).Method(0)
fmt.Printf("%+v\n", f2)
Run Code Online (Sandbox Code Playgroud)
但是,结果f2是a reflect.Method,而不是函数指针.:(
这里适当的语法是什么?
您可以使用方法表达式,它将返回一个以接收者作为第一个参数的函数.
f2 := (*x).hello2
fmt.Printf("%+v\n", f2)
f2(&x{}, 123)
Run Code Online (Sandbox Code Playgroud)
否则,您可以将函数调用包装在接受x作为参数的函数中.
f2 := func(val *x) {
val.hello2(123)
}
Run Code Online (Sandbox Code Playgroud)
或者关闭现有x价值.
val := &x{}
f2 := func() {
val.hello2(123)
}
Run Code Online (Sandbox Code Playgroud)
关于 Go 函数调用和闭包的相关阅读:Russ Cox 的“Go 1.1 Function Calls”(其中也详细介绍了 Go1)。
https://docs.google.com/document/d/1bMwCey-gmqZVTpRax-ESeVuZGmjwbocYs1iHplK-cjo/pub