How do I pass and a method as a parameter or callback function

I thought I understood how passing a method as an argument works, clearly I don’t. I am trying to get the outer function to call a method on the receiver which I declared explicitly. Here is my code;

package main

type Foo struct {
}

func (f Foo) sum(a, b int) int {
    return a + b
}

func main() {
    var foo Foo
    bar := func(fn func(f Foo)) {
        fn(foo)
    }
    bar(Foo.sum(foo, 2, 2))
}

Error

cannot use Foo.sum(foo, 2, 2) (value of type int) as func(f Foo) value in argument to bar

I am doing something wrong but I just can’t figure it out.

I think you might be looking for something like this: Go Playground - The Go Programming Language

You have to also include the types of the parameters and return type (i.e., the function signature of Foo.sum is func(Foo, int, int) int, so it cannot be passed to bar as a func(Foo)). You’re also calling Foo.sum when you pass it to bar, so instead of passing the Foo.sum function to bar, you’re passing the result of Foo.sum which is an int, hence you get that error.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.