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