methodstypesstructgofirst-class-functions

Using function names as parameters


In Go, you can pass functions as parameters like callFunction(fn func). For example:

package main

import "fmt"

func example() {
    fmt.Println("hello from example")
}

func callFunction(fn func) {
    fn()
}    

func main() {
    callFunction(example)
}

But is it possible to call a function when it's a member of a struct? The following code would fail, but gives you an example of what I'm talking about:

package main

import "fmt"

type Example struct {
    x int
    y int
}

var example Example

func (e Example) StructFunction() {
    fmt.Println("hello from example")
}

func callFunction(fn func) {
    fn()
}    

func main() {
    callFunction(example.StructFunction)
}

(I know what I'm trying to do in that example is a little odd. The exact problem I have doesn't scale down to a simple example very well, but that's the essence of my problem. However I'm also intrigued about this from an academic perspective)


Solution

  • Go 1.0 does not support the use of bound methods as function values. It will be supported in Go 1.1, but until then you can get similar behaviour through a closure. For example:

    func main() {
        callFunction(func() { example.StructFunction() })
    }
    

    It isn't quite as convenient, since you end up duplicating the function prototype but should do the trick.