在方法内部默认情况下会取消对指针的引用吗? [英] Are pointers dereferenced by default inside of methods?

查看:51
本文介绍了在方法内部默认情况下会取消对指针的引用吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Go中的struct方法感到困惑.我按照他们的教程进行学习:

I'm confused by methods on structs in Go. I've following along in a tutorial in which they have:

func (p *Page) save() error {
    filename := p.Title + ".txt"
    return ioutil.WriteFile(filename, p.Body, 0600)
}

据我了解, p 是指针,例如,在检索属性之前,您需要取消引用指针:

From my understanding, p is pointer and you would need to dereference the pointer before retrieving a property for example:

filename := (*p).Title + ".txt"

这对我来说唯一有意义的方法是,点的作用类似于C ++中的-> .我想念什么?

The only way this makes sense to me is if the dot is acting like -> in C++. What am I missing?

推荐答案

是的,该结构的指针会自动取消引用.根据选择器规范:

Yes, the pointer to the struct is automatically dereferenced. From the spec on selectors:

以下规则适用于选择器:

The following rules apply to selectors:

  1. 对于类型为 T * T 的值 x ,其中 T 不是指针或接口类型, xf 表示 T 中最浅深度的字段或方法有这样的 f 的地方.如果不完全是一个 f 与最浅的深度,选择器表达式是非法的.
  1. For a value x of type T or *T where T is not a pointer or interface type, x.f denotes the field or method at the shallowest depth in T where there is such an f. If there is not exactly one f with shallowest depth, the selector expression is illegal.

...

  1. 作为例外,如果 x 的类型是命名的指针类型,而(* x).f 是表示字段的有效选择器表达式(但不是方法), x.f (* x).f 的简写.
  1. As an exception, if the type of x is a named pointer type and (*x).f is a valid selector expression denoting a field (but not a method), x.f is shorthand for (*x).f.

因此,以下两个语句是相同的(首选第一个):

Therefore, the following two statements are the same (with the first being preferred):

filename := p.Title + ".txt"
filename := (*p).Title + ".txt"

这篇关于在方法内部默认情况下会取消对指针的引用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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