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?
source to share
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.
source to share