英文:
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,这个输出让我感到困惑。在golang中,(&t).value和t.value有什么区别?
英文:
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?
答案1
得分: 1
选择器表达式p.f,其中p是指向某个结构类型的指针,f是该结构类型的字段,是(*p).f的简写。
你的表达式(&t)的结果是指针类型*test的值。所以(&t).value是(*(&t)).value的简写。
选择器的规则如下:
- 对于类型为
T或*T(其中T不是指针或接口类型)的值x,x.f表示在T中最浅层次存在的字段或方法f。如果最浅层次存在的f不止一个,则选择器表达式是非法的。 - 对于类型为
I的值x(其中I是接口类型),x.f表示x的动态值中具有名称f的实际方法。如果在I的方法集中没有名称为f的方法,则选择器表达式是非法的。 - 作为例外,如果
x的类型是定义的指针类型,并且(*x).f是一个有效的选择器表达式,表示一个字段(而不是方法),则x.f是(*x).f的简写。 - 在所有其他情况下,
x.f是非法的。 - 如果
x是指针类型且具有空值nil,并且x.f表示一个结构字段,则对x.f进行赋值或评估会导致运行时恐慌。 - 如果
x是接口类型且具有空值nil,调用或评估方法x.f会导致运行时恐慌。
更多信息请参考Selectors。
英文:
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:
>
> 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论