英文:
Passing http.ResponseWriter by value or reference?
问题
假设我有一个中央方法,它向http.ResponseWriter添加特定的标头。我不想使用HandleFunc包装器。
我想知道,我是否应该通过引用发送ResponseWriter。那么,哪种方式是正确的:
addHeaders(&w)
还是
addHeaders(w)
换句话说:
func addHeaders(w *http.ResponseWriter) {...}
还是
func addHeaders(w http.ResponseWriter) {...}
根据我的理解,我会说第一种版本是正确的,因为我不想创建ResponseWriter的副本。但是我没有看到任何将ResponseWriter作为引用传递的代码,想知道为什么。
谢谢!
英文:
Assume I'm having a central method which adds a specific header to the http.ResponseWriter. I don't want to use a HandleFunc wrapper.
I wonder, whether I'd send in the ResponseWriter by reference. So, what would be correct:
addHeaders(&w)
or
addHeaders(w)
Asked differently:
func addHeaders(w *http.ResponseWriter) {...}
or
func addHeaders(w http.ResponseWriter) {...}
From my understanding, I'd say the first version would be correct, as I don't want to create a copy of ResponseWriter. But I haven't seen any code where ResponseWriter is passed by reference and wonder why.
Thanks!
答案1
得分: 23
http.ResponseWriter
是一个接口。你想要传递它的值,因为它内部包含一个指向实际 Writer 的指针。你几乎不需要一个接口的指针。
看一下标准处理函数的签名:
func(http.ResponseWriter, *http.Request)
注意 ResponseWriter 不是一个指针。
英文:
http.ResponseWriter
is an interface. You want to pass its value, since it internally contains a pointer to the actual Writer. You almost never want a pointer to an interface.
Look at what a standard handler func's signature is:
func(http.ResponseWriter, *http.Request)
Notice that ResponseWriter isn't a pointer.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论