Why does the `http` package need to be referenced by address?

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

Why does the `http` package need to be referenced by address?

问题

client := &http.Client{}client := http.Client{} 之间有什么区别?两者似乎都可以正常工作。为什么 Go 文档(http://golang.org/pkg/net/http/) 使用 &http.Client{}

在包级别上通过地址引用似乎不会有任何区别。这是为了确保使用单例的 Client 还是其他原因吗?

英文:

What's the difference between client := &http.Client{} and client := http.Client{}? Both seem to work fine. Why do the Go Docs(http://golang.org/pkg/net/http/) use &http.Client{}?

I seems like referencing by address at a package level shouldn't make any difference. Is this to make sure a singleton Client is used or something?

答案1

得分: 2

从语法上讲,第一种方式将分配Client结构,并声明一个指向它的指针,而第二种方式只是声明了一个Client值。

在实现层面上,由于编译器的逃逸分析机制,没有太大的区别。如果指向客户端对象的指针逃逸了函数,那么无论声明的方式如何,对象都将在堆上分配。如果Go编译器确定对象仅在函数内部使用(即不逃逸),则可以在堆栈上声明它,无论声明的方式如何。

所以两种方式都可以正常工作。

现在,关于http.Client,请考虑它是一个重量级对象:它引用了一个缓存http连接的http.Transport对象。文档中指出,应尽可能重用Client对象。一个http.Client值并不是真正意义上的可复制对象。

在我看来,更好的风格是保持对该对象的指针,因为这样清楚地表明该对象不是一个短暂的临时变量,并且在函数之间传递它更方便。

英文:

Syntactically, the first will allocate the Client structure, and declare a pointer on it, while the second will just declare a Client value.

Now, at the implementation level, there is not much difference, because of the compiler escape analysis mechanism. If a pointer to the client object escapes the function, then the object will be allocated on the heap, whatever the way it has been declared. If the Go compiler establishes that the object is purely local to the function (i.e. does not escape), it may be declared on the stack, whatever the way it has been declared.

So both ways work fine.

Now, regarding http.Client, consider it is an heavy object: it refers to an http.Transport object which caches the http connections. The documentation says that a Client object should be reused as far as possible. A http.Client value is not really meant to be copied.

IMO, it is therefore better style to keep a pointer on the object, since it makes clear that the object is not a short-lived temporary variable, and more convenient to pass it as a parameter between functions.

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

发表评论

匿名网友

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

确定