2016-10-04 83 views
1

我试图创造一种功能类似于快递(的NodeJS)途径方法在Go类型:使用回调和功能中去

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

在这个例子中,我要“富” (类型)与上述方法中的匿名函数相同。这是我使用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 
     }) 
} 

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

+0

边注,但可能相关 - 在使用中间件模式与一般语法,可能是熟悉酷围棋web框架方面快递是https://echo.labstack.com。 – syllabix

+0

@syllabix我想创建一个Echo的副本:) – adamSiwiec

回答

6

您现在处于正确的轨道 - 在您使用的上下文中为功能创建一个类型,增加了设计意图,更重要的是增加了类型安全性。

你只需要修改你例子有点为它来编译:

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

}