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
x
of typeT
or*T
whereT
is not a pointer or interface type,x.f
denotes the field or method at the shallowest depth inT
where there is such anf
. If there is not exactly onef
with shallowest depth, the selector expression is illegal.- For a value
x
of typeI
whereI
is an interface type,x.f
denotes the actual method with namef
of the dynamic value ofx
. If there is no method with namef
in the method set ofI
, the selector expression is illegal.- 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
.- In all other cases,
x.f
is illegal.- If
x
is of pointer type and has the value nil andx.f
denotes a struct field, assigning to or evaluatingx.f
causes a run-time panic.- If
x
is of interface type and has the valuenil
, calling or evaluating the methodx.f
causes a run-time panic.