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

时间:2015-07-22 11:07:37

标签: go

我正在尝试创建一个具有方法接收器的函数的函数指针。但是,我无法弄清楚如何让它工作(如果可能的话)?

基本上,我有以下内容:

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

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

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

syntax error: unexpected func, expecting semicolon or newline

3 个答案:

答案 0 :(得分:11)

如果要创建指向方法的函数指针,可以使用两种方法。第一个基本上是将带有两个参数的方法转换为一个带有一个的函数:

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

第二种方式将"绑定"方法接收者的功能:

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

游乐场:http://play.golang.org/p/ctovxsFV2z

答案 1 :(得分:1)

对于我们这些习惯于C中typedef用于函数指针的人更熟悉的例子:

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

答案 2 :(得分:0)

我很可能偏离目标(只是在Golang上启动),但是如果创建指针然后检查类型该怎么办?

pfun := Bar 
fmt.Println("type of pfun is:", reflect.TypeOf(pfun))

那么看来您可以正确声明指针的类型:
https://play.golang.org/p/SV8W0J9JDuQ