gpt4 book ai didi

go - 在 go 中使用回调和函数作为类型

转载 作者:IT王子 更新时间:2023-10-29 01:21:19 26 4
gpt4 key购买 nike

我正在尝试创建一种类似于 Go 中的 Express (NodeJS) 路由方法的函数:

app.get("route/here/", func(req, res){
res.DoStuff()
});

在此示例中,我希望“foo”(类型)与上述方法中的匿名函数相同。这是我使用 Go 的失败尝试之一:

type foo func(string, string)

func bar(route string, io foo) {
log.Printf("I am inside of bar")
// run io, maybe io() or io(param, param)?
}

func main() {
bar("Hello", func(arg1, arg2) {
return arg + arg2
})
}

我该如何解决我的困境?我不应该使用类型而使用其他类型吗?我有哪些选择?

最佳答案

您走在正确的轨道上 - 在您正在使用的上下文中为函数创建类型可以增加更清晰的设计意图和额外的类型安全性。

你只需要稍微修改一下你的例子就可以编译了:

package main

import "log"

//the return type of the func is part of its overall type definition - specify string as it's return type to comply with example you have above
type foo func(string, string) string

func bar(route string, io foo) {

log.Printf("I am inside of bar")
response := io("param", "param")
log.Println(response)

}

func main() {

bar("Hello", func(arg1, arg2 string) string {
return arg1 + arg2
})

}

关于go - 在 go 中使用回调和函数作为类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39843134/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com