Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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
like image 769
riklund Avatar asked Jul 22 '15 11:07

riklund


People also ask

How do you send a pointer to a function in Go?

Go programming language allows you to pass a pointer to a function. To do so, simply declare the function parameter as a pointer type.

How can a function pointer be declared?

You can use a trailing return type in the declaration or definition of a pointer to a function. For example: auto(*fp)()->int; In this example, fp is a pointer to a function that returns int .

Does Go have function pointers?

Go has pointers. A pointer holds the memory address of a value. The type *T is a pointer to a T value.

How do I declare a pointer variable in Golang?

* Operator also termed as the dereferencing operator used to declare pointer variable and access the value stored in the address. & operator termed as address operator used to returns the address of a variable or to access the address of a variable to a pointer.


2 Answers

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

like image 95
Ainar-G Avatar answered Sep 27 '22 19:09

Ainar-G


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

like image 45
EdH Avatar answered Sep 27 '22 17:09

EdH