pointers - 为什么 http.Request 参数必须是一个指针?

标签 pointers go

package main

import (
    "net/http"
)

func main() {
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request){
        w.Write([]byte("hello world"))
    })
    http.ListenAndServe(":8000", nil)
}

如果我删除 http.Request 中的 *:

github.com/creating_web_app_go/main.go:8: cannot use func literal (type func(http.ResponseWriter, http.Request)) as type func(http.ResponseWriter, *http.Request) in argument to http.HandleFunc

我对 Go 和指针都很陌生。

所以问题是, 为什么 http.Request 必须是指针而不是 func literal?谁能以最简单的方式解释这一点,也许可以引用源代码?

最佳答案

因为它是一个大结构。复制它会很昂贵。所以它是一个指向结构的指针,当结构很大时,这在 Go 中很常见。它也有一些状态,所以如果它被复制可能会造成混淆。成为 func 文字是没有意义的;我不明白为什么这是一个选项。

关于pointers - 为什么 http.Request 参数必须是一个指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31145564/

相关文章:

C++ Integer 从 *char[] 中删除字符串

cryptography - 如何从 Golang 中的字符串中获取 MD5 哈希?

golang 数据库事务 : continue if single exec statement fails

更改指向第一个指针的另一个指针的值

c - C : Why do I have to explicitly reassign head and tail even when they are not changed? 中的双向链表

go - 如何为CORS问题启用gqlgen服务器?

go - golang接口(interface)如何转换数组?

pointers - Go指针交换问题

c - 为什么打印出 char 指针会产生整个数组而不是指针的内存地址?

c++ - 从 C++ 中的 wxTextCtrl 获取条目文本