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

ada*_*iec 2 go

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

app.get("route/here/", func(req, res){
    res.DoStuff()
});    
Run Code Online (Sandbox Code Playgroud)

在这个例子中,我希望"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
        })
}
Run Code Online (Sandbox Code Playgroud)

我怎么能解决我的困境?我不应该使用类型并使用其他东西吗?我有什么选择?

syl*_*bix 7

您处于正确的轨道 - 在您使用它的上下文中为func创建类型会增加更清晰的设计意图,更重要的是增加类型安全性.

您只需修改一下示例即可进行编译:

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

}
Run Code Online (Sandbox Code Playgroud)