尝试理解 Go 中的处理函数

问题描述 投票:0回答:1

我试图做这个练习:https://go.dev/doc/articles/wiki/来自Golang文档,但我不明白一些东西。在文章的第二部分中,当我们开始使用“net/http”包时,我们写了这个(我在这里留下了更完整的代码:https://go.dev/doc/articles/wiki/part2.go) :

 func viewHandler(w http.ResponseWriter, r *http.Request) {

    title := r.URL.Path[len("/view/"):]

    p, _ := loadPage(title)

    fmt.Fprintf(w, "<h1>%s</h1><div>%s</div>", p.Title, p.Body)

}


func main() {

    http.HandleFunc("/view/", viewHandler)

    log.Fatal(http.ListenAndServe(":8080", nil))

}

我不明白为什么 viewHandler 位于 http.HandleFunc 的参数中,而没有上面定义的两个参数。因为,viewHandler的定义中有两个参数:w和r?什么时候/谁完成?

go http handler
1个回答
0
投票

Go 支持使用函数签名作为其他函数的参数。这是 Go 中的一个强大功能,被称为“一流函数。”

在 Go 中,函数是一等公民,这意味着您可以将函数作为参数传递给其他函数,甚至可以从函数返回函数。此功能对于创建高阶函数和处理回调特别有用。

这是一个较短的示例:

type BinaryOperation func(int, int) int

func Apply(operation BinaryOperation) int {
    return operation(5, 5)
}

func main() {
    // Define an addition function inline
    sum := Apply(func(a, b int) int { return a + b })
    fmt.Println(sum) // 10

    // Define a subtraction function inline
    difference := Apply(func(a, b int) int { return a - b })
    fmt.Println(difference) // 0
}
© www.soinside.com 2019 - 2024. All rights reserved.