Why assign a link to a structure in go?

I am going through the code on this page:

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

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

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

      

Why use &

when creating this structure?

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

r := Rectangle{}

      

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

+3


source to share


3 answers


The difference lies in the type of your variable.

client := &http.Client{

      

does client

like*http.Client



and

client := http.Client{

      

creates http.Client

.

+7


source


The top one returns a pointer. It's a Go idiom instead of using the new one. The second is just a value object. If you need a pointer, use the top.

Check out the effective go doc for more information on this



http://golang.org/doc/effective_go.html#allocation_new

+3


source


In object-oriented programming, in order for an object to have a dynamic lifetime (i.e. not tied to the current function call), it must be dynamically allocated at a location other than the current stack frame, so you manipulate the object through a pointer. This is such a general scheme that in many object-oriented languages, including Java, Python, Ruby, Objective-C, Smalltalk, JavaScript, and others, you can only deal with pointers to objects, never "object as value" itself. (Some languages, although C ++, for example, allows you to have "objects as values", it comes with the RAII idiom, which adds some complexity.)

Go is not an object-oriented language, but its ability to define custom types and define methods that work on that custom type can be very useful for classes and methods. Returning a pointer to type from the constructor function allows the "object" to have a dynamic lifetime.

+2


source







All Articles