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

问题描述:

I am attempting to create a sort of function that is similar to the Express (NodeJS) route method in Go:

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

In this example I want "foo" (the type) to be the same as the anonymous function in the above method. Here is one of my failed attempts using 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
        })
}

How might I fix my dilemma? Should I not use a type and use something else? What are my options?

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

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

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

  type foo func(string,string)
 
func bar(route string,io foo){
 log.Printf  (“我在酒吧里面”)
 //运行io,也许是io()或io(param,param)?
} 
 
func main(){
 bar(“ Hello”,func(arg1  ,arg2){
返回arg + arg2 
})
} 
  code>  pre> 
 
 

如何解决我的难题? 我不应该使用类型并使用其他东西吗? 我有什么选择? p> div>

You are on the right track - creating a type for a func on the context you are using it adds clearer design intent and more importantly additional type safety.

You just need to modify you example a bit for it to compile:

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

}

package main

import (
    "fmt"
    "log"
)

type foo func(string, string)

func bar(route string, callback foo) bool {
 //...logic

  /* you can return the callback to use the 
     parameters and also in the same way you 
     could verify the bar function
   */
    callback("param", "param")
    return true
}

func main() {
    fmt.Println("Hello, playground")

    res := bar("Hello", func(arg1, arg2 string) {
        log.Println(arg1 + "_1")
        log.Println(arg2 + "_2")
    })

    fmt.Println("bar func res: ", res)
}