`(&t).value` 和 `t.value` 在 Golang 中有什么区别?其中 t 是一个结构体。

huangapple go评论71阅读模式
英文:

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的简写。

选择器的规则如下:

  1. 对于类型为T*T(其中T不是指针或接口类型)的值xx.f表示在T中最浅层次存在的字段或方法f。如果最浅层次存在的f不止一个,则选择器表达式是非法的。
  2. 对于类型为I的值x(其中I是接口类型),x.f表示x的动态值中具有名称f的实际方法。如果在I的方法集中没有名称为f的方法,则选择器表达式是非法的。
  3. 作为例外,如果x的类型是定义的指针类型,并且(*x).f是一个有效的选择器表达式,表示一个字段(而不是方法),则x.f(*x).f的简写。
  4. 在所有其他情况下,x.f是非法的。
  5. 如果x是指针类型且具有空值nil,并且x.f表示一个结构字段,则对x.f进行赋值或评估会导致运行时恐慌。
  6. 如果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.


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.

huangapple
  • 本文由 发表于 2022年4月1日 23:54:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/71709714.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定