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