如何在Go中声明指向方法的函数指针

问题描述:

I am trying to create function pointer to a function that has a method receiver. However, I can't figure out how to get it to work (if it is possible)?

Essentially, I have the following:

type Foo struct {...}
func (T Foo) Bar bool {
   ... 
}

type BarFunc (Foo) func() bool // Does not work.

The last line of the code gives the error

syntax error: unexpected func, expecting semicolon or newline

我正在尝试创建指向具有方法接收器的函数的函数指针。 但是,我无法弄清楚如何使其工作(如果可能)? p>

本质上,我具有以下内容: p>

   type Foo struct {...} 
func(T Foo)Bar bool {
 ... 
} 
 
type BarFunc(Foo)func()bool //不起作用。
  代码>  pre> 
 
 

代码的最后一行给出了错误 p>

 语法错误:意外的函数,期望使用分号或换行符
  代码>  pre> 
  div>

If you want to create a function pointer to a method, you have two ways. The first is essentially turning a method with two arguments into a function with one:

type Summable int

func (s Summable) Add(n int) int {
    return s+n
}

var f func(s Summable, n int) int = (Summable).Add

// ...
fmt.Println(f(1, 2))

The second way will "bind" the function to the method's receiver:

s := Summable(1)
var f func(n int) int = s.Add
fmt.Println(f(2))

Playground: http://play.golang.org/p/ctovxsFV2z.

And for an example more familiar to those of us used to a typedef in C for function pointers:

package main

import "fmt"

type DyadicMath func (int, int) int  // your function pointer type

func doAdd(one int, two int) (ret int) {
    ret = one + two;
    return
}

func Work(input []int, addthis int, workfunc DyadicMath) {
    for _, val := range input {
        fmt.Println("--> ",workfunc(val, addthis))
    }
}

func main() {
    stuff := []int{ 1,2,3,4,5 }
    Work(stuff,10,doAdd)

    doMult := func (one int, two int) (ret int) {
        ret = one * two;
        return
    }   
    Work(stuff,10,doMult)

}

https://play.golang.org/p/G5xzJXLexc