我试图从 Golang 文档中进行此练习:https://go.dev/doc/articles/wiki/,但我不明白某些内容。在文章的第二部分中,当我们开始使用“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))
}
Run Code Online (Sandbox Code Playgroud)
我不明白为什么 viewHandler 位于 http.HandleFunc 的参数中而没有上面定义的两个参数。因为,viewHandler的定义中有两个参数:w和r?什么时候/谁完成?
Go 支持使用函数签名作为其他函数的参数。这是 Go 中被称为“一流函数”的强大功能。
\n在 Go 中,函数是一等公民,这意味着您可以将函数作为参数传递给其他函数,甚至可以从函数返回函数。此功能对于创建高阶函数和处理回调特别有用。
\n这是一个较短的示例:
\ntype BinaryOperation func(int, int) int\n\nfunc Apply(operation BinaryOperation) int {\n return operation(5, 5)\n}\n\nfunc main() {\n // Define an addition function inline\n sum := Apply(func(a, b int) int { return a + b })\n fmt.Println(sum) // 10\n\n // Define a subtraction function inline\n difference := Apply(func(a, b int) int { return a - b })\n fmt.Println(difference) // 0\n}\nRun Code Online (Sandbox Code Playgroud)\n此外,理解回调的概念可以帮助您理解这段代码。
\n回调是一个常见的编程概念,涉及将一个函数作为参数传递给另一个函数,并在发生特定事件或满足特定条件时执行该函数。回调通常用于实现异步操作、事件处理和定时任务等场景。
\n一个简单的回调示例\xef\xbc\x9a
\nfunc eventHandler(event string, callback func(string)) {\n fmt.Println("Event:", event)\n callback(event)\n}\n\nfunc main() {\n eventHandler("Button Click", func(event string) {\n fmt.Println("Handling", event)\n })\n\n eventHandler("File Save", func(event string) {\n fmt.Println("Saving", event)\n })\n}\nRun Code Online (Sandbox Code Playgroud)\n
| 归档时间: |
|
| 查看次数: |
111 次 |
| 最近记录: |