下面的代碼獲取一個函數指針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
,不是函數指針。 :(
什麼是適當的語法在這裏?
這是一個很好的答案! – 2016-08-20 00:17:42