Go: is it possible to return pointer to a function

huangapple go评论86阅读模式
英文:

Go: is it possible to return pointer to a function

问题

以下是代码的翻译:

对于以下代码:

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

是否有一种方法可以返回函数的指针而不是直接返回函数本身?(类似于 return &a

Playground链接:https://play.golang.org/p/IobCtRjVVX

英文:

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

答案1

得分: 6

是的,只要你正确转换类型即可:

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

而且不使用命名类型:

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))
}
英文:

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

得分: 2

访问其他包:

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

package main

import "fmt"

var f = fmt.Println
var p2f = &f

func main() {
    (*p2f)("it works")
}
英文:

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

huangapple
  • 本文由 发表于 2017年2月28日 01:30:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/42492123.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定