Go func调用困惑

标签 go

在这段代码中:

handler := func(w http.ResponseWriter, r *http.Request) {
    io.WriteString(w, "<html><body>Hello World!</body></html>")

func 关键字在做什么?我一直在阅读 Tour of Go,我对这里发生的事情感到困惑。

已编辑:添加了导入列表和函数,它属于

这里是函数的一部分:

func ExampleResponseRecorder() {
handler := func(w http.ResponseWriter, r *http.Request) {
    io.WriteString(w, "<html><body>Hello World!</body></html>")
}

req := httptest.NewRequest("GET", "http://example.com/foo", nil)
w := httptest.NewRecorder()
handler(w, req)

resp := w.Result()
body, _ := ioutil.ReadAll(resp.Body)

fmt.Println(resp.StatusCode)
fmt.Println(resp.Header.Get("Content-Type"))
fmt.Println(string(body))

// Output:
// 200
// text/html; charset=utf-8
// <html><body>Hello World!</body></html>
 }

import (
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"net/http/httptest"
)

最佳答案

func 定义一个 closure , 一个匿名函数。 handler 是一个包含此函数引用的变量,稍后您可以通过在括号中传递参数来调用它:

handler(w, req)

关于Go func调用困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47954407/

相关文章:

go - golang 谷歌 Protocol Buffer 中的错误

http - 接受图像标题请求

go - Go 比较字节和 rune 的规则是什么?

http - 去重试 403 禁止的 http 请求?

email - 是否有任何成熟的库来解析电子邮件 header ? -去

serialization - `fmt` 包的函数是否支持数组的格式化程序?

string - 如何根据 rune 而不是 Go 中的字节获取子字符串索引?

concurrency - Func 不会运行;增量 channel

go - 在 Go 中执行 shell 命令

go - 在 Go 中测量 FLOPS