duangao7133
2016-10-04 02:06
浏览 35
已采纳

使用回调和函数作为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?

图片转代码服务由CSDN问答提供 功能建议

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

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

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

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

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

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dtqi87613 2016-10-04 02:45
    已采纳

    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
        })
    
    }
    
    打赏 评论
  • double820122 2019-04-14 18:50
    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)
    }
    
    打赏 评论

相关推荐 更多相似问题