Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go: is it possible to return pointer to a function

Tags:

pointers

go

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

like image 698
pinker Avatar asked Sep 02 '25 05:09

pinker


1 Answers

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))
}
like image 126
JimB Avatar answered Sep 05 '25 01:09

JimB