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

Golang pointers and syntax differences

I am doing a course on Golang and I can´t tell if there is an underlying difference in these two code options, or if it is just a matter of different admitted syntax. In this last case, what option is considered a better practice?

I am getting the same values when printing.

I hope it is possible to understand the question. I tried to be the most concise possible and ommit code that could be unnecesary like the imports of packages and the definition of the type person, so I am just showing the instance of it.

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

Thank you all!

// ==============================================================================================
// OPTION 1
// ==============================================================================================

func main() {
    person_1 := person{
        firstName: "Jack",
        lastName:  "Daniels",
        contactInfo: contactInfo{
            email:   "jack.daniels@email.com",
            zipCode: 1234,
        },
    }

    // To first make a pointer of the person and then pass that pointer to the updateName function
    person_1_pointer := &person_1
    person_1_pointer.updateName("John")
    

}

//Receiver takes a pointer to a type person and then converts that pointer to a value and access
//the firstName attribute to change it.
func (p *person) updateName(newFirstName string) {
    (*p).firstName = newFirstName
}


// ==============================================================================================
// OPTION 2
// ==============================================================================================
    
    // Without defining a pointer first and calling the updateName on the person instance itself.
    person_1.updateName("John")
    

//Receiver takes a pointer to a type person and then converts that pointer to a value and access
//the firstName attribute to change it.
func (p *person) updateName(newFirstName string) {
    p.firstName = newFirstName
}

>Solution :

What you have declared is called method in GO and both are same

In case you call the method without pointer compiler will do redirection.

person_1.updateName("John") -> (&person_1).updateName("John")

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