Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 841
laurent Avatar asked Feb 02 '13 16:02

laurent


3 Answers

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.

like image 119
Denys Séguret Avatar answered Sep 28 '22 07:09

Denys Séguret


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

Check the effective go doc for more about this

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

like image 32
masebase Avatar answered Sep 28 '22 08:09

masebase


In object-oriented programming, in order for an object to have dynamic lifetime (i.e. not tied to the current function call), it needs to be dynamically allocated in a place other than the current stack frame, thus you manipulate the object through a pointer. This is such a common pattern 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 with an "object as a value" itself. (Some languages though, like C++, do allow 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 operates on that custom type, can be made to work very much like classes and methods. Returning a pointer to the type from the "constructor" function allows the "object" to have a dynamic lifetime.

like image 29
newacct Avatar answered Sep 28 '22 08:09

newacct