【问题标题】:Difference between the types of accessing pointer values in golanggolang中访问指针值类型的区别
【发布时间】:2022-01-07 03:13:10
【问题描述】:

考虑下面的例子

type Employee struct {
    Firstname string
    // other fields
}

func (e *Employee) SetName(name string) {
   e.Firstname = name // type 1
   (*e).firstName = name // type 2
}

类型 1 和类型 2 在这里访问属性的方式有什么区别?我们什么时候应该使用一个而不是另一个?

【问题讨论】:

    标签: go pointers struct reference


    【解决方案1】:

    类型 1 是类型 2 的简写。使用简写符号。

    这是quote from the specification

    如果 x 的类型是已定义的指针类型并且 (*x).f 是表示字段(但不是方法)的有效选择器表达式,则 x.f 是 (*x).f 的简写。

    【讨论】:

      猜你喜欢
      • 2017-06-21
      • 1970-01-01
      • 1970-01-01
      • 2017-02-13
      • 1970-01-01
      • 2019-07-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多