Go的指针何时解除引用? [英] When do Go's pointers dereference themselves
问题描述
我刚刚开始潜入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
我一直无法在spec中找到这个指针部分非常短,甚至不触及解引用。任何澄清解除引用go的指针的规则都会很棒!
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!
推荐答案
选择器表达式(例如 xf
)会这样做:
选择器自动解除引用指针为结构。如果
x
是一个指向结构的指针,
xy
是的简写。 * X).Y
;如果字段y
也是一个指向结构体的指针,则xyz
是
的简写(*(* x).y).z
,依此类推。如果x
包含* A
类型的匿名字段,其中
A
也是一个结构类型,xf
是(* xA).f
的快捷键。
Selectors automatically dereference pointers to structs. If
x
is a pointer to a struct,x.y
is shorthand for(*x).y
; if the fieldy
is also a pointer to a struct,x.y.z
is shorthand for(*(*x).y).z
, and so on. Ifx
contains an anonymous field of type*A
, whereA
is also a struct type,x.f
is a shortcut for(*x.A).f
.
索引操作指定可以对数组指针进行索引:
The definition of the indexing operation specifies that an array pointer may be indexed:
对于
类型的A
或* A
其中A
是一个数组类型,或者是S
其中S
是一个切片类型
For a of type
A
or*A
whereA
is an array type, or for a of typeS
whereS
is a slice type
这篇关于Go的指针何时解除引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!