How do I declare a function pointer to a method in Go

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


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

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 value of s (at the time of evaluation) to the Summable receiver method Add, and then assign it to the variable f:

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

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

Any changes to s after f is assigned will have no affect on the result: https://play.golang.org/p/UhPdYW5wUOP

Tags:

Go