在方法内部默认情况下会取消对指针的引用吗? [英] Are pointers dereferenced by default inside of methods?
问题描述
我对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:
- 对于类型为
T
或* T
的值x
,其中T
不是指针或接口类型,xf
表示T
中最浅深度的字段或方法有这样的f
的地方.如果不完全是一个f
与最浅的深度,选择器表达式是非法的.
- For a value
x
of typeT
or*T
whereT
is not a pointer or interface type,x.f
denotes the field or method at the shallowest depth inT
where there is such anf
. If there is not exactly onef
with shallowest depth, the selector expression is illegal.
...
- 作为例外,如果
x
的类型是命名的指针类型,而(* x).f
是表示字段的有效选择器表达式(但不是方法),x.f
是(* x).f
的简写.
- 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屋!