【发布时间】:2013-03-12 02:09:30
【问题描述】:
以下代码获取指向函数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,而不是函数指针。 :(
这里的适当语法是什么?
【问题讨论】:
标签: go function-pointers member-function-pointers