0

Given the struct:

type A struct {
    total int
}

and the func

(a *A) add func (i int, j int) (int x) {
    a.total += i+j
    return i+j
  }

I would like to create a variable pointing to the func and invoke it via that variable. I'm having trouble defining the signature for the variable that includes the instance of the struct.

Why do this? Because I want to create an array of func pointers and iterate through it it calling them in sequence. I can have different arrays to accomplish different tasks using my func building blocks.

These two don't compile:

thisfunc func (a *A) (i int, b int) (x int)
thisfunc (a *A) func (i int, b int) (x int)

This one compiles but doesn't include the struct instance and when invoking thisfunc, a is missing - no struct instance, i.e null pointer dereference.

thisfunc func (i int, b int) (x int)

I would like to do something like this:

thisfunc = a.add
b := thisfunc(1,2)

Please help me define a variable thisfunc whose signature matches a.add.

2
  • It's not impossible, but it might be needlessly complex. Is there a reason that thisfunc can't be a function that takes a struct pointer, rather than a method whose receiver is that struct pointer? e.g. func thisfunc(a *A, i, j int) Commented Dec 29, 2015 at 18:10
  • That indeed was what I did. Much easier. It might have been good to know what the signature was, but getting on with life is more important Commented Dec 30, 2015 at 19:08

1 Answer 1

3

I think what you're looking for are "Method Values"

Given type A:

type A struct {
    total int
}

func (a *A) add(i int, j int) int {
    a.total += i + j
    return i + j
}

While the method expression for (*A).add technically has a signature of

func(*A, int, int)

You can use the value of the add method as a function with the signature

func(int int)

Which can be assigned like so:

var thisfunc func(int, int) int

a := A{}
thisfunc = a.add
thisfunc(3, 4)

http://play.golang.org/p/_3WztPbL__

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.