3
votes

For the following code:

package main

import "fmt"

type intFunc func(int) int

var t = func() intFunc {
        a := func(b int) int { return b}
        return a
    }

func main() {
    fmt.Println(t()(2))
   }

Is there a way to return the pointer to the function instead of the function directly? (something like return &a)?

The playground is here: https://play.golang.org/p/IobCtRjVVX

2
Yes, but why would you need to/want to? Functions are first class, even though I should check the assembly, they probably behave more like reference types than data. - Elias Van Ootegem
@EliasVanOotegem: you may want to be able to pass a function pointer as an argument to be set. It's a similar situation as when you need a pointer to a pointer. - JimB
@JimB: Fair enough: setting a value on a pointer argument. But go has multiple return values, I hardly ever set values on arguments because I can just return 2 or 3 values if I really want/need to. And the OP is specifically asking about returning a pointer to a function - Elias Van Ootegem

2 Answers

4
votes

Yes, as long as you convert the types correctly:

https://play.golang.org/p/3R5pPqr_nW

type intFunc func(int) int

var t = func() *intFunc {
    a := intFunc(func(b int) int { return b })
    return &a
}

func main() {
    fmt.Println((*t())(2))
}

And without the named type:

https://play.golang.org/p/-5fiMBa7e_

var t = func() *func(int) int {
    a := func(b int) int { return b }
    return &a
}

func main() {
    fmt.Println((*t())(2))
}
2
votes

Accessing other packages:

https://play.golang.org/p/X20RtgpEzqL

package main

import "fmt"

var f = fmt.Println
var p2f = &f

func main() {
    (*p2f)("it works")
}