Search code examples
referencestructinitializationgo

Why assign a reference to a struct in go?


I'm having a look at the code at this page:

http://golang.org/pkg/net/http/

And there's one thing I don't understand - at some point, a new structure is created and initialized like this:

client := &http.Client{
    CheckRedirect: redirectPolicyFunc,
}

Why use & when creating this structure?

I've also read this blog post and structs are initialized like this:

r := Rectangle{}

What is the difference between both and how should I know which one to use?


Solution

  • The difference is in the type of your variable.

    client := &http.Client{
    

    makes client of type *http.Client

    while

    client := http.Client{
    

    builds a http.Client.