For a primary expression x
that is not a package name, the selector expression
x.f
denotes the field or method f
of the value x
(or sometimes *x
; see below). The identifier f
is called the (field or method) selector; it must not be the blank identifier. The type of the selector expression is the type of f
. If x
is a package name, see the section on qualified identifiers.
A selector f
may denote a field or method f
of a type T
, or it may refer to a field or method f
of a nested anonymous field of T
. The number of anonymous fields traversed to reachf
is called its depth in T
. The depth of a field or method f
declared in T
is zero. The depth of a field or method f
declared in an anonymous field A
in T
is the depth of f
in A
plus one.
The following rules apply to selectors:
- For a value
x
of typeT
or*T
whereT
is not an 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. - For a variable
x
of typeI
whereI
is an interface type,x.f
denotes the actual method with namef
of the value assigned tox
. If there is no method with namef
in the method set ofI
, the selector expression is illegal. - In all other cases,
x.f
is illegal. - If
x
is of pointer type and has the valuenil
andx.f
denotes a struct field, assigning to or evaluatingx.f
causes a run-time panic. - If
x
is of interface type and has the valuenil
, calling or evaluating the methodx.f
causes a run-time panic.
Selectors automatically dereference pointers to structs. If x
is a pointer to a struct, x.y
is shorthand for (*x).y
; if the field y
is also a pointer to a struct, x.y.z
is shorthand for (*(*x).y).z
, and so on. If x
contains an anonymous field of type *A
, where A
is also a struct type, x.f
is shorthand for (*x.A).f
.
原文 http://golang.org/ref/spec#Selectors