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?
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.