传递 http.ResponseWriter 是按值还是按引用?

huangapple go评论78阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2014年3月4日 05:10:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/22157514.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定