Difference between the types of accessing pointer values in golang

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

Difference between the types of accessing pointer values in golang

问题

在这里,type 1 和 type 2 访问属性的方式有什么区别?我们应该在什么情况下使用其中一种而不是另一种?

type 1 和 type 2 是等效的,它们都用于访问结构体属性。在这个例子中,e.Firstname(*e).Firstname 都是访问 Employee 结构体的 Firstname 属性的方式。

type 1 使用了隐式解引用,即 e.Firstname,它会自动解引用指针并访问属性。这种方式更加简洁和直观,因此在大多数情况下,推荐使用 type 1。

type 2 使用了显式解引用,即 (*e).Firstname,它需要手动解引用指针并访问属性。这种方式在某些特定情况下可能会有用,例如当你需要在解引用之前执行其他操作时。

总的来说,type 1 是更常用和推荐的方式,因为它更简洁和易读。只有在特殊情况下,才需要使用 type 2。

英文:

Consider the below example

type Employee struct {
    Firstname string
    // other fields
}

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

What is the difference between type 1 and type 2 ways of accessing properties here? When should we use one over the other?

答案1

得分: 4

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

这是规范中的引用

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

英文:

Type 1 is a shorthand for type 2. Use the shorthand notation.

Here's the quote from the specification:

> 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.

huangapple
  • 本文由 发表于 2022年1月7日 11:13:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/70616176.html
匿名

发表评论

匿名网友

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

确定