为什么必须将http.Request参数用作指针? [英] Why must the http.Request argument be a pointer?

查看:160
本文介绍了为什么必须将http.Request参数用作指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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:无法在http的参数中使用func文字(类型func(http.ResponseWriter,http.Request))作为func(http.ResponseWriter,* http.Request)类型. HandleFunc

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和指针都很陌生.

I'm very new to both Go and pointers.

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

So the Question is, why must http.Request be a pointer rather than a func literal? Can anyone explain this in the simplest way possible, with perhaps a reference to source code?

推荐答案

因为它是一个大型结构.复制它会很昂贵.因此,它是指向结构的指针,当结构较大时,这在Go中很常见.它还具有某种状态,因此如果将其复制,则可能会造成混淆.成为一个有趣的字面意义是没有意义的.我不明白为什么这是一个选择.

Because it's a large struct. Copying it would be expensive. So it's a pointer to a struct, which is common in Go when structs are large. Also it has some state, so it would likely be confusing if it were copied. It would make no sense to be a func literal; I don't understand why that would be an option.

这篇关于为什么必须将http.Request参数用作指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆