2013-03-12 52 views
5

下面的代碼獲取一個函數指針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) 

然而,由此產生f2reflect.Method,不是函數指針。 :(

什麼是適當的語法在這裏?

回答

7

您可以使用方法表達式,它會返回一個函數,它接收的第一個參數。

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) 
} 
+0

這是一個很好的答案! – 2016-08-20 00:17:42

相關問題