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

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

Closures in Go - declaring functions that take functions as parameters

问题

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

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

代码:

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

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

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

Code:

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

答案1

得分: 0

看一下为什么它无法编译可能会有帮助,将最内层的函数提取为一个参数,如 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)) {
        //这没有意义,因为你无法访问b
        //fmt.Printf("debug: foo in main is %d and %d", foo, b)
        fmt.Printf("debug: foo in main is %d", foo)

        //你可以调用你的函数参数,如下所示
        a(6)
        a(7)
    }))
}

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

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

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

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:

确定