即使p是指向结构的指针,Go在哪里定义p.Field(与(* p).Field相对)还是有效的语法? [英] Where does Go define that p.Field (as opposed to (*p).Field) is a valid syntax even when p is a pointer to a struct?
问题描述
这是我的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
作为法律语法?
When p
is of type *Person
, i.e. a pointer to Person
, how is it legal to access its field Name
without dereferencing it? I see all Go tutorials using the syntax p.Name
instead of (*p).Name
but where exactly the Go language defines p.Person
as a legal syntax?
推荐答案
以下规则适用于选择器:
The following rules apply to selectors:
[...],如果 x
的类型是命名的指针类型,而(* x).f
是表示字段的有效选择器表达式(但不是)一个方法), xf
是(* x).f
的简写.
[...] 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
.
语言规范可帮助您使用指针语法,以使您感觉在某些情况下甚至没有使用指针.解引用指针以访问其字段是其中之一.如果可以寻址,也可以调用在非指针值上具有指针接收器的方法,请参见
The language spec helps you with the pointer syntax to make it feel you're not even using pointers in some cases. Dereferencing a pointer to access its field is one of them. Also you can call methods that have pointer receiver on non-pointer values if they are addressable, see Calling a method with a pointer receiver by an object instead of a pointer to it?
您还可以索引和切片数组指针,例如如果 a
是指向数组类型的指针:
Also you can index and slice array pointers, e.g. if a
is a pointer to array type:
-
a [x]
是(* a)[x]
的简写 - 和
a [low:high]
是(* a)[low:high]
的简写.
a[x]
is shorthand for(*a)[x]
- and
a[low : high]
is shorthand for(*a)[low : high]
.
这篇关于即使p是指向结构的指针,Go在哪里定义p.Field(与(* p).Field相对)还是有效的语法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!