2018-10-25 13:02
浏览 192


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函数中将函数作为参数传递。 这是我的代码:

 // TODO在此处启动该方法
  <  / pre> 


  func route(){
 app.Call(“  /“,controllers.Index())


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

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

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • doulu3808 2018-10-25 13:09

    It's entirely up to you if you create a named type. Technically you are defining a type even if you do it anonymously in the signature (the type is func() in your code). Whether or not it needs to be defined with a name is up to you and depends on your use case and needs.

    Whether or not you define a named type, the function signatures must match (you can't pass a func(http.ResponseWriter, http.Request) to a func() argument), and you have to pass the function rather than calling it and passing its return value (which it does not have):

    // Correct arguments required
    func Call(path string, method func(http.ResponseWriter, http.Request)) {
        // TODO launch the method here
    func routes() {
         // Index() calls the function, you just want to pass a reference to it
        app.Call("/", controllers.Index)
    解决 无用
    打赏 举报

相关推荐 更多相似问题