golang 中的 (&t).value 和 t.value 有什么区别? t 是一个结构
what is the different between (&t).value and t.value in golang? t is a struct
我在 golang 中有这样一个结构,如下所示:
type test struct {
value int
}
当我尝试这个时
t := test{1}
fmt.Println((&t).value)
fmt.Println(t.value)
编译器没有报错,和我一样的输出1,
这个输出 confused me.What is different between (&t).value and t.value in golang?
选择器表达式 p.f
其中 p
是指向某个结构类型的指针,而 f
是该结构类型的字段 shorthand for (*p).f
.
您的表达式 (&t)
产生指针类型 *test
的值。所以这使得 (&t).value
成为 (*(&t)).value
的 shorthand。
The following rules apply to selectors:
- 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.
- 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.
- 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 and x.f
denotes a struct field, assigning to or evaluating x.f
causes a
run-time panic.
- If
x
is of interface type and has the value nil
, calling or
evaluating the method x.f
causes a run-time panic.
我在 golang 中有这样一个结构,如下所示:
type test struct {
value int
}
当我尝试这个时
t := test{1}
fmt.Println((&t).value)
fmt.Println(t.value)
编译器没有报错,和我一样的输出1, 这个输出 confused me.What is different between (&t).value and t.value in golang?
选择器表达式 p.f
其中 p
是指向某个结构类型的指针,而 f
是该结构类型的字段 shorthand for (*p).f
.
您的表达式 (&t)
产生指针类型 *test
的值。所以这使得 (&t).value
成为 (*(&t)).value
的 shorthand。
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.