Go的指针何时解除引用? [英] When do Go's pointers dereference themselves

查看:177
本文介绍了Go的指针何时解除引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始潜入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 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 indexing operation specifies that an array pointer may be indexed:


对于类型的A * A 其中 A 是一个数组类型,或者是 S 其中 S 是一个切片类型

For a of type A or *A where A is an array type, or for a of type S where S is a slice type

这篇关于Go的指针何时解除引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆