I am learning Go and I am reading Go's official documentation about net/http
, and I write following code from doc for test:
package main
import (
"net/http"
"fmt"
)
func main() {
client := &http.Client{}
resp, _ := client.Get("http://example.com")
fmt.Println(resp)
}
http.Client
is a struct, but I do not know why there is a &
pointer prefixed. I think creating a http.Client
reference is not necessary. And why does the client
variable have a Get
method? I am reading the source code of net/http
, it defines the Client
struct below:
type Client struct {
Transport RoundTripper
CheckRedirect func(req *Request, via []*Request) error
Jar CookieJar
Timeout time.Duration
}
The Client
struct does not have a Get
method defined; why does the client
variable have a Get
method?
I would really take the Go Tour to get a feeling of the language and its basic syntax first.
The type declaration you quoted only contains the fields of the struct, but not its methods. Methods are defined elsewhere, like functions but with a receiver added which designates the type they belong to. For example the definition of
Client.Get()
method is this:The part before the method name is called the receiver, and that designates the type the method belogns to (
*Client
in this example). See Spec: Method declarations for more details.The
&
is an address operator, it takes the address of its operand. In this case the local variableclient
will be of type*http.Client
.http.Client{}
is a composite literal which creates a value of the struct typehttp.Client
, and&
takes the address of the anonymous variable where this struct value is stored:It is used so that the
client
variable will be a pointer to anhttp.Client
value, one that is encouraged to be shared and reused:And if
client
is a pointer, you are free to pass it around to other functions, only the pointer value will be copied, not the pointedhttp.Client
struct, so the struct itself (thehttp.Client
value) will be reused. Should you not use a pointer, if you would pass it to other functions, the struct itself would be copied and not reused.Note that in this simple example it doesn't really matter, as even though all methods of
http.Client
are declared with pointer receiver, you can still call pointer methods on non-pointer variables, asclient.Get()
would be a shorthand for(&client).Get()
. This is mentioned in Spec: Calls:So even though the
&
address operator is not needed in this simple example, it's good to keep the habit of using it, should the example grow or should you write code where this does matter (e.g. you pass around the created client).