Home > OS >  Difference between the types of accessing pointer values in golang
Difference between the types of accessing pointer values in golang

Time:01-07

Consider the below example

type Employee struct {
    Firstname string
    // other fields
}

func (e *Employee) SetName(name string) {
   e.Firstname = name // type 1
   (*e).firstName = name // type 2
}

What is the difference between type 1 and type 2 ways of accessing properties here? When should we use one over the other?

CodePudding user response:

Type 1 is a shorthand for type 2. Use the shorthand notation.

Here's the quote from the specification:

if the type of x is a defined pointer type and (*x).f is a valid selector expression denoting a field (but not a method), x.f is shorthand for (*x).f.

  •  Tags:  
  • Related