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.
The following rules apply to selectors:
- For a value
xof typeTor*TwhereTis not a pointer or interface type,x.fdenotes the field or method at the shallowest depth inTwhere there is such anf. If there is not exactly onefwith shallowest depth, the selector expression is illegal.- For a value
xof typeIwhereIis an interface type,x.fdenotes the actual method with namefof the dynamic value ofx. If there is no method with namefin the method set ofI, the selector expression is illegal.- As an exception, if the type of
xis a defined pointer type and(*x).fis a valid selector expression denoting a field (but not a method),x.fis shorthand for(*x).f.- In all other cases,
x.fis illegal.- If
xis of pointer type and has the value nil andx.fdenotes a struct field, assigning to or evaluatingx.fcauses a run-time panic.- If
xis of interface type and has the valuenil, calling or evaluating the methodx.fcauses a run-time panic.
