Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why dereference only to reference again in Go

In gorilla/sessions there is the following code:

func (s *CookieStore) New(r *http.Request, name string) (*Session, error) {
    session := NewSession(s, name)
    opts := *s.Options
    session.Options = &opts
    ...

Where s.Options is of type *sessions.Options:

type CookieStore struct {
    ...
    Options *Options // default configuration
}

And sessios.Session.Options is also of type *sessions.Options:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

type Session struct {
    ...
    Options *Options
    ...
}

My question is, what is the point of dereferencing s.Options and then assigning its reference to session.Options? Why not just do:

func (s *CookieStore) New(r *http.Request, name string) (*Session, error) {
    session := NewSession(s, name)
    session.Options = s.Options
    ...

Is this to make sure the dereferenced value of s.Options is copied over to session.Options, and not the actual reference therefore avoiding both objects pointing to the same thing?

>Solution :

It is to prevent two pointers from pointing to the same location.

session := NewSession(s, name)
opts := *s.Options

At this point, opts contains a copy of s.Options. Then:

session.Options = &opts

This will set session.Options to an options object that is different from s.Options, but whose contents are initialized from s.Options.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading