这是我的 Go 程序。
package main
import (
"fmt"
)
type Person struct {
Name string
}
func main() {
p := &Person{"Jack"}
// The following statement makes sense. We dereference the
// pointer to reach the Person object and then retrieve its Name
// field.
fmt.Println((*p).Name)
// But the following statement does not make sense. How does
// this code work by retrieving the Name field directly from the
// pointer without dereferencing it?
fmt.Println(p.Name)
}
这是输出。
$ go run foo.go
Jack
Jack
当 p
是 *Person
类型时,即指向 Person
的指针,如何访问其字段 Name 是合法的
没有取消引用它?我看到所有使用语法 p.Name
而不是 (*p).Name
的 Go 教程,但 Go 语言确切地定义了 p.Person
作为合法语法?
最佳答案
The following rules apply to selectors:
[...] 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
.
语言规范帮助您使用指针语法,让您感觉在某些情况下您甚至没有使用指针。取消引用指针以访问其字段就是其中之一。如果它们是可寻址的,您也可以调用在非指针值上具有指针接收器的方法,参见 Calling a method with a pointer receiver by an object instead of a pointer to it?
您还可以对数组指针进行索引和 slice ,例如如果 a
是指向数组类型的指针:
a[x]
是(*a)[x]
的简写
- 和
a[low : high]
是(*a)[low : high]
的简写。
关于pointers - Go 在哪里定义 p.Field(与 (*p).Field 相对)是有效语法,即使 p 是指向结构的指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43729893/