在Go语言中,闭包(Closures)是一种声明函数参数为函数的方式。

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

Closures in Go - declaring functions that take functions as parameters

问题

我一直在尝试弄清楚为什么这段代码不起作用,但不确定。沙盒中的错误是:

  1. main.go:16: 语法错误:意外的 {,期望 )

代码:

  1. package main
  2. import "fmt"
  3. type handler func(a func(b int))
  4. func HandleSomething(h handler) {
  5. //...
  6. //d := h(5)
  7. //h(5)
  8. // ...
  9. }
  10. func main() {
  11. var foo int
  12. HandleSomething(handler(func(func(b int){
  13. fmt.Printf("debug: foo in main is %d and %d", foo, b)
  14. })))
  15. }
英文:

I've been trying to figure out why this is not working but am not sure. The error in the sandbox is

  1. main.go:16: syntax error: unexpected {, expecting )

Code:

  1. package main
  2. import "fmt"
  3. type handler func(a func(b int))
  4. func HandleSomething(h handler) {
  5. //...
  6. //d := h(5)
  7. //h(5)
  8. // ...
  9. }
  10. func main() {
  11. var foo int
  12. HandleSomething(handler(func(func(b int){
  13. fmt.Printf("debug: foo in main is %d and %d", foo, b)
  14. })))
  15. }

答案1

得分: 0

看一下为什么它无法编译可能会有帮助,将最内层的函数提取为一个参数,如 https://play.golang.org/p/QPBturZ6GG 所示。

我认为你可能在寻找以下类似的内容,但它不会做太多事情 https://play.golang.org/p/2tEEwoZRC6

  1. package main
  2. import "fmt"
  3. type handler func(a func(b int))
  4. func HandleSomething(h handler) {
  5. //...
  6. //d := h(5)
  7. //h(5)
  8. // ...
  9. }
  10. func main() {
  11. var foo int
  12. HandleSomething(handler(func(a func(b int)) {
  13. //这没有意义,因为你无法访问b
  14. //fmt.Printf("debug: foo in main is %d and %d", foo, b)
  15. fmt.Printf("debug: foo in main is %d", foo)
  16. //你可以调用你的函数参数,如下所示
  17. a(6)
  18. a(7)
  19. }))
  20. }

以下示例可能会给你更多的玩耍空间

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

英文:

To see why it won't compile it might be helpful to pull your innermost function out into an argument as shown at https://play.golang.org/p/QPBturZ6GG

I think you are looking for something like the following, but it won't do much
https://play.golang.org/p/2tEEwoZRC6

  1. package main
  2. import "fmt"
  3. type handler func(a func(b int))
  4. func HandleSomething(h handler) {
  5. //...
  6. //d := h(5)
  7. //h(5)
  8. // ...
  9. }
  10. func main() {
  11. var foo int
  12. HandleSomething(handler(func(a func(b int)) {
  13. //This doesn't make sense as you don't have access to b
  14. //fmt.Printf("debug: foo in main is %d and %d", foo, b)
  15. fmt.Printf("debug: foo in main is %d", foo)
  16. //You can call your function argument like
  17. a(6)
  18. a(7)
  19. }))
  20. }

The following example might give you something more to play with

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

huangapple
  • 本文由 发表于 2015年5月1日 08:15:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/29979858.html
匿名

发表评论

匿名网友

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

确定