当Go语言的指针自动解引用时

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

When do Go's pointers dereference themselves

问题

我最近刚开始学习Go语言,有一个主要的困惑点:我很难理解何时需要显式地解引用指针。

例如,我知道.运算符会处理解引用指针:

ptr := new(SomeStruct)
ptr.Field = "foo" //自动解引用

在哪些其他情况下,Go语言会这样做呢?例如,对于数组,它似乎也会这样做:

ptr := new([5][5]int)
ptr[0][0] = 1

我在规范中找不到这个内容,指针部分的内容非常简短,甚至没有涉及解引用。如果能对Go语言指针解引用的规则进行解释,那就太好了!

英文:

I just started diving into Go recently and I have one major point of confusion: I am struggling to understand when exactly it is necessary to dereference a pointer explicitly.

For example I know that the . operator will handle dereferencing a pointer

ptr := new(SomeStruct)
ptr.Field = "foo" //Automatically dereferences

In what other scenarios does go do this? It seems to for example, with arrays.

ptr := new([5][5]int)
ptr[0][0] = 1

I have been unable to find this in the spec, the section for pointers is very short and doesn't even touch dereferencing. Any clarification of the rules for dereferencing go's pointers would be great!

答案1

得分: 56

选择器表达式(例如 x.f)可以实现以下功能:

选择器会自动解引用指向结构体的指针。如果 x 是指向结构体的指针,那么 x.y 等同于 (*x).y;如果字段 y 也是指向结构体的指针,那么 x.y.z 等同于 (*(*x).y).z,依此类推。如果 x 包含一个类型为 *A 的匿名字段,其中 A 也是一个结构体类型,那么 x.f(*x.A).f 的简写。

索引表达式的定义规定了可以对数组指针进行索引:

对于指向数组类型的指针 a

  • a[x] 等同于 (*a)[x]
英文:

The selector expression (e.g. x.f) does that:

> Selectors automatically dereference pointers to structs. If x is a pointer to a struct,
> x.y is shorthand for (*x).y; if the field y is also a pointer to a struct, x.y.z is
> shorthand for (*(*x).y).z, and so on. If x contains an anonymous field of type *A, where
> A is also a struct type, x.f is a shortcut for (*x.A).f.

The definition of the index expressions specifies that an array pointer may be indexed:

> For a of pointer to array type:
>
> - a[x] is shorthand for (*a)[x]

huangapple
  • 本文由 发表于 2012年11月24日 01:43:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/13533681.html
匿名

发表评论

匿名网友

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

确定