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.
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")