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

(*variable) and *&variable, what is the difference?

i am learning GO using exercism.com and reading the recommended documentation and articles from the syllabus.

now i am in struct and found the next code

package main

import "fmt"

type Employee struct {
  firstName, lastName string
  salary              int
  fullTime            bool
}

func main() {
  employee := &Employee{
    firstName: "Walddys",
    lastName:  "Dorrejo",
    salary:    1200,
    fullTime:  true,
  }
  fmt.Println("firstName", (*employee).firstName)
}

but by error, I typed fmt.Println("firstName", *&employee.firstName), which bring me the same result that the previous used in the block of code.

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

My question is, if exist any different of using this pointer or is the same?

>Solution :

&x generates a pointer to x, while *p dereferences the pointer p. So effectively * and & cancel each other out, for example the two statements v := *&x and v := x are identical.

That means that *&employee.firstName is identical to employee.firstName.

And where employee is a pointer to a struct and firstName is a field of that struct, the expression employee.firstName is actually a shorthand for (*employee).firstName.

This means that *&employee.firstName is also identical to (*employee).firstName.


Note that you should always prefer to use the shorthand notation.

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