Selectors
For a primary expression
xthat is not a package name, the selector expressionx.fdenotes the field or method
fof the valuex(or sometimes*x; see below). The identifierfis called the (field or method) selector; it must not be the blank identifier. The type of the selector expression is the type off. Ifxis a package name, see the section on qualified identifiers.
This section is mostly definitional. But let’s illustrate. Given the following code:
type Person struct {
Name string
}
func (p *Person) Greet() {
fmt.Println("Hello,", p.Name)
}
var p = Person{Name: "Bob"}
These would be examples of some primary expressions of the form described:
p.Name // `Name` is a field selector, with type `string`
p.Greet // `Greet` is a method selector, with type `func()`
Note that the field or method selector cannot be blank. Blank identifiers are asymmetric in this sense:
type Phantom struct {
_ string // Blank identifier is valid as a field name
}
var p Phantom
p._ // Invalid: However, you cannot reference the blank identifier with a selector. That's kind of the point...
Quotes from The Go Programming Language Specification Version of August 2, 2023