Poniższy kod pobiera wskaźnik do funkcji hello
i drukuje go:Jak uzyskać wskaźnik funkcji dla wpisanej funkcji w programie?
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)
}
Jednak gdybym un-skomentować sekcję na dole, w kompilacji błędy, mówiąc:
> ./junk.go:14: undefined: hello2
Tak próbowałem:
i := &x{}
f2 := &i.hello2
fmt.Printf("%+v\n", f2)
... ale błędy z:
> ./junk.go:15: method i.hello2 is not an expression, must be called
Ok, więc może muszę bezpośrednio odnoszą się do oryginalnego typu:
f2 := x.hello2
fmt.Printf("%+v\n", f2)
Nope:
> ./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)
Ten rodzaj prac:
i := &x{}
f2 := reflect.TypeOf(i).Method(0)
fmt.Printf("%+v\n", f2)
Jednak uzyskany f2
to reflect.Method
, a nie wskaźnik funkcji. :(
Jaka jest właściwa składnia tutaj?
To jest doskonała odpowiedź! –