这是我的围棋程序。
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而不对其取消引用?我看到所有的Go教程都使用语法p.Name而不是(*p).Name,但是Go语言到底在哪里将p.Person定义为合法语法?
发布于 2017-05-02 12:07:06
以下规则适用于选择器:
..。如果x.f (*x).f.的类型是命名指针类型,并且x是表示字段(而不是方法)的有效选择器表达式,则是for的简写形式
该语言规范帮助您处理指针语法,使其感觉在某些情况下您甚至没有使用指针。取消引用指针以访问其字段就是其中之一。如果非指针值是可寻址的,则还可以调用具有指针接收器的方法,请参见Calling a method with a pointer receiver by an object instead of a pointer to it?
您还可以索引和切片数组指针,例如,如果a是指向数组类型的指针:
a[x]是(*a)[x]a[low : high]是(*a)[low : high].的缩写
https://stackoverflow.com/questions/43729893
复制相似问题