繁体   English   中英

Go中的闭包-声明以函数为参数的函数

[英]Closures in Go - declaring functions that take functions as parameters

我一直在试图找出为什么这不起作用,但不确定。 沙箱中的错误是

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

码:

package main

import "fmt"

type handler func(a func(b int))

func HandleSomething(h handler)  {
    //...
    //d := h(5)
//h(5)
    // ...
}

func main() {
    var foo int
    HandleSomething(handler(func(func(b int){
            fmt.Printf("debug: foo in main is %d and %d", foo, b)
    })))
}

要了解为什么它无法编译,将最里面的函数放入参数中可能会有所帮助,如https://play.golang.org/p/QPBturZ6GG所示

我认为您正在寻找类似以下内容的内容,但不会做太多https://play.golang.org/p/2tEEwoZRC6

package main

import "fmt"

type handler func(a func(b int))

func HandleSomething(h handler) {
    //...
    //d := h(5)
    //h(5)
    // ...
}

func main() {
    var foo int
    HandleSomething(handler(func(a func(b int)) {
        //This doesn't make sense as you don't have access to b
        //fmt.Printf("debug: foo in main is %d and %d", foo, b)
        fmt.Printf("debug: foo in main is %d", foo)

        //You can call your function argument like
        a(6)
        a(7)
    }))
}

以下示例可能会给您带来更多乐趣

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM