英文:
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")
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论