登录
首页 >  Golang >  Go问答

将函数作为参数传递到 Go 编程语言的函数

来源:stackoverflow

时间:2024-03-20 23:21:36 331浏览 收藏

在 Go 语言中,可以通过将函数作为参数传递给其他函数,从而实现函数式编程。要传递函数作为参数,需要确保函数签名匹配目标函数所需的参数。例如,要将 `index()` 函数传递给 `call()` 函数,需要修改 `call()` 函数的签名以接受一个 `func(http.ResponseWriter, http.Request)` 类型的参数。同时,在调用 `call()` 函数时,需要传递 `index()` 函数的引用,而不是调用该函数并传递其返回值。

问题内容

我想在 go 函数中传递一个函数作为参数。这是我的代码:

func call(path string, method func()) {
    // todo launch the method here
}

当我想调用这个函数时,我想这样做:

func routes() {
    app.call("/", controllers.index())
}

index() 方法是:

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

创建 type 并将此 type 作为参数传递是一个好主意吗?


解决方案


是否创建命名类型完全取决于您。从技术上讲,即使您在签名中匿名执行,您也正在定义一个类型(代码中的类型为 func() )。是否需要用名称来定义它取决于您,并且取决于您的用例和需求。

无论您是否定义命名类型,函数签名都必须匹配(您不能将 func(http.responsewriter, http.request) 传递给 func() 参数),并且必须传递函数而不是调用它并传递它的返回值(它没有):

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

今天关于《将函数作为参数传递到 Go 编程语言的函数》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>