How do you get a function pointer to a typed function in go?

The following code gets a pointer to a function helloand prints it:

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

However, if I do not comment on the section below, we compile the errors by saying:

> ./junk.go:14: undefined: hello2

So I tried:

  i := &x{}
  f2 := &i.hello2
  fmt.Printf("%+v\n", f2)

... but these are errors with:

> ./junk.go:15: method i.hello2 is not an expression, must be called

Ok, maybe I need to directly refer to the original type:

  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)

This type of work:

  i := &x{}
  f2 := reflect.TypeOf(i).Method(0)
  fmt.Printf("%+v\n", f2)

However, the resulting f2is reflect.Method, not a function pointer.: (

What is the syntax here?

+5
source share
2 answers

You can use method expressions that return a function that takes a receiver as the first argument.

f2 := (*x).hello2
fmt.Printf("%+v\n", f2)

f2(&x{}, 123)

, x .

f2 := func(val *x) {
    val.hello2(123)
}

, x.

val := &x{}

f2 := func() {
    val.hello2(123)
}
+7
+2

All Articles