gpt4 book ai didi

pointers - 默认情况下,指针是否在方法内部取消引用?

转载 作者:IT老高 更新时间:2023-10-28 13:06:56 26 4
gpt4 key购买 nike

我对 Go 结构中的方法感到困惑。我在他们的教程中跟随:

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

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

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

这对我来说有意义的唯一方法是,如果点的行为类似于 C++ 中的 ->。我错过了什么?

最佳答案

是的,指向结构的指针会自动取消引用。来自 spec on selectors :

The following rules apply to selectors:

  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. 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.

因此,以下两种说法相同(首选第一种):

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

关于pointers - 默认情况下,指针是否在方法内部取消引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30786206/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com