簡體   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