pointers - Why is http.Client{} prefixed with &? -


i learning go , reading go's official documentation net/http, , write following code doc test:

package main  import (     "net/http"     "fmt" )  func main() {     client := &http.client{}     resp, _ := client.get("http://example.com")      fmt.println(resp) } 

http.client strut, not know why there & pointer prefixed, think create http.client reference not necessary, , why client variable have get method? reading source code of "net/http", defined client struct below:

type client struct {     transport roundtripper     checkredirect func(req *request, via []*request) error     jar cookiejar     timeout time.duration } 

the client struct did not have get method defined, why client variable have get method?

i take go tour feeling of language , basic syntax first.

the type declaration quoted contains fields of struct, not methods. methods defined elsewhere, functions receiver added designates type belong to. example definition of client.get() method this:

func (c *client) get(url string) (resp *response, err error) {     req, err := newrequest("get", url, nil)     if err != nil {         return nil, err     }     return c.do(req) } 

the part before method name called receiver, , designates type method belogns (*client in example). see spec: method declarations more details.

the & address operator, takes address of operand. in case local variable client of type *http.client. http.client{} composite literal creates value of struct type http.client, , & takes address of anonymous variable struct value stored:

taking address of composite literal generates pointer unique variable initialized literal's value.

it used client variable pointer http.client value, 1 encouraged shared , reused:

the client's transport typically has internal state (cached tcp connections), clients should reused instead of created needed. clients safe concurrent use multiple goroutines.

and if client pointer, free pass around other functions, pointer value copied, not pointed http.client struct, struct (the http.client value) reused. should not use pointer, if pass other functions, struct copied , not reused.

note in simple example doesn't matter, though methods of http.client declared pointer receiver, can still call pointer methods on non-pointer variables, client.get() shorthand (&client).get(). mentioned in spec: calls:

if x addressable , &x's method set contains m, x.m() shorthand (&x).m().

so though & address operator not needed in simple example, it's keep habit of using it, should example grow or should write code matter (e.g. pass around created client).


Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -