4

Is there anyway to make a map of function pointers, but functions that take recievers? I know how to do it with regular functions:

package main

func someFunc(x int) int {
    return x
}

func main() {
    m := make(map[string]func(int)int, 0)
    m["1"] = someFunc
    print(m["1"](56))
}

But can you do that with functions that take recievers? Something like this (though I've tried this and it doesn't work):

package main

type someStruct struct {
    x int
}

func (s someStruct) someFunc() int {
    return s.x
}

func main() {
    m := make(map[string](someStruct)func()int, 0)
    s := someStruct{56}
    m["1"] = someFunc
    print(s.m["1"]())
}

An obvious work around is to just pass the struct as a parameter, but that's a little dirtier than I would have liked

2
  • 1
    No - the methods aren't free-floating functions, you can't have a reference to a method without an associated instance, and you can't then execute it against a different instance. You could do this using reflection. Commented Aug 3, 2017 at 0:30
  • 1
    You actually can have a reference for a method without an associated instance: golang.org/ref/spec#Method_expressions. See my answer for an example. Commented Aug 3, 2017 at 2:17

1 Answer 1

7

You can do that using Method Expressions:

https://golang.org/ref/spec#Method_expressions

The call is a bit different, since the method expression takes the receiver as the first argument.

Here's your example modified:

package main

type someStruct struct {
    x int
}

func (s someStruct) someFunc() int {
    return s.x
}

func main() {
    m := make(map[string]func(someStruct)int, 0)
    s := someStruct{56}
    m["1"] = (someStruct).someFunc
    print(m["1"](s))
}

And here's a Go playground for you to test it:

https://play.golang.org/p/PLi5A9of-U

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.