4

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

3
  • 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. Commented Feb 27, 2017 at 18:31
  • @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. Commented Feb 27, 2017 at 18:38
  • @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 Commented Feb 27, 2017 at 18:39

2 Answers 2

6

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))
}
Sign up to request clarification or add additional context in comments.

Comments

2

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")
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.