Selectors
…
- As an exception, if the type of
x
is a defined pointer type and(*x).f
is a valid selector expression denoting a field (but not a method),x.f
is shorthand for(*x).f
.
I find this wording to be confusing. That probably means some of you do, too. So here goes my best attempt at explaining it.
“if the type of x
is a defined pointer type” refers to something like this:
type Person struct { // Person is a defined type
Name string
}
var x = &Person{} // x is of type *Person, not Person, thus it is a "defined pointer type"
Since x
is a pointer, the complete, canonical way to access the Name
field on x
as defined above would be:
name := (*x).Name
That is to say, we have to dereference x
to get at its pointed-to value. That’s what (*x)
does. Then we can access the field.
What the spec is telling us is that as a shorthand for this, we can use x
in place of (*x)
:
name := x.Name
Quotes from The Go Programming Language Specification Version of August 2, 2023