doubei2340
2018-10-25 13:02
浏览 258
已采纳

在go函数中将函数作为参数传递

I want to pass a function as a parameter in a go function. Here is my code:

func Call(path string, method func()) {
    // TODO launch the method here
}

When I want to call this function, I want to do this:

func routes() {
    app.Call("/", controllers.Index())
}

And the Index() method is:

func Index(res http.ResponseWriter, req http.Request) {
    userAgent := req.Header.Get("User-Agent")
    fmt.Fprintf(res, "You're User-Agent is %s", userAgent)
}

Is a good idea to create a type and pass this type as parameter ?

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

我想在go函数中将函数作为参数传递。 这是我的代码:</ p>

  func调用(路径字符串,方法func()){
 // TODO在此处启动该方法
} 
 </ code> <  / pre> 
 
 

当我想调用此函数时,我想这样做:</ p>

  func route(){
 app.Call(“  /“,controllers.Index())
} 
 </ code> </ pre> 
 
 

Index()</ code>方法为:</ p>

  func索引(res http.ResponseWriter,req http.Request){
 userAgent:= req.Header.Get(“ User-Agent”)
 fmt.Fprintf(res,“ You'  re User-Agent是%s“,userAgent)
} 
 </ code> </ pre> 
 
 

创建 type </ code>并传递此< code> type </ code>作为参数?</ p> </ div>

1条回答 默认 最新

相关推荐 更多相似问题