Home > Software engineering >  what is the different between (&t).value and t.value in golang? t is a struct
what is the different between (&t).value and t.value in golang? t is a struct

Time:04-02

I have such a struct in golang like below:

type test struct {
    value int
}

and when I tried this

t := test{1}
fmt.Println((&t).value)
fmt.Println(t.value)

the compiler did not report an error,and I got the same output of 1, this output confused me.What is different between (&t).value and t.value in golang?

CodePudding user response:

The selector expression p.f where p is a pointer to some struct type and f is a field of that struct type is shorthand for (*p).f.

Your expression (&t) results in a value of the pointer type *test. So that makes (&t).value the shorthand for (*(&t)).value.


Selectors:

The following rules apply to selectors:

  1. For a value x of type T or *T where T is not a pointer or interface type, x.f denotes the field or method at the shallowest depth in T where there is such an f. If there is not exactly one f with shallowest depth, the selector expression is illegal.
  2. For a value x of type I where I is an interface type, x.f denotes the actual method with name f of the dynamic value of x. If there is no method with name f in the method set of I, the selector expression is illegal.
  3. As an exception, 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.
  4. In all other cases, x.f is illegal.
  5. If x is of pointer type and has the value nil and x.f denotes a struct field, assigning to or evaluating x.f causes a run-time panic.
  6. If x is of interface type and has the value nil, calling or evaluating the method x.f causes a run-time panic.
  • Related